我是Java新手,想了解更多关于继承的知识。假设
class Vehicle{
public void move(){
System.out.println(“Vehicles can move”);
}
}
class MotorBike extends Vehicle{
public void move(){
System.out.println(“MotorBike can move and accelerate tool”);
}
}
class Test{
public static void main(String[] args){
Vehicle vh=new MotorBike();
vh.move();
vh=new Vehicle();
vh.move();
}
}
当我们第一次执行vh.move()
时,它会打印MotorBike can move and Accelerator tool
。第二次打印 Vehicles can move
。
可以称为方法重写。因为我们在两个类中有相同的方法名称。
但是,如果两个类有不同的方法,那么应该调用哪个方法呢?我想说的是,
class Vehicle{
public void move(){
System.out.println(“Vehicles can move”);
}
}
class MotorBike extends Vehicle{
public void part(){
System.out.println(“MotorBike can move and accelerate tool”);
}
}
class Test{
public static void main(String[] args){
vehicle a = new vehicle();
Vehicle vh=new MotorBike();
}
}
在第一种情况下vehicle a = new Vehicle();
它调用 move() 并
第二种情况会是什么?如果我这样做 `Vehicle vh=new MotorBike(); 应该调用哪个方法? move() 还是part()?
最佳答案
在第二种情况下,即使你定义了一个额外的方法part(),你也只能调用move()方法(它继承自Vehicle),因为你已经告诉编译器vh是一个Vehicle(它并不不知道这是一辆摩托车)
Vehicle vh = new MotorBike(); // from now on, vh is a Vehicle - we don't know it's a MotorBike
vh.move(); // this is fine
vh.part(); // this will not compile
如果你想调用part()方法,那么你必须将变量定义为MotorBike:
MotorBike vh = new MotorBike(); // now we know it's a MotorBike
vh.part(); // this is ok now
关于Java继承概念,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31754286/