Java中最重要的内容可以通过一个示例简单地解释?
如果超类和子类具有包含参数的同名方法。JVM根据用于调用方法的对象来调用相应的方法。即,如果调用该方法的当前对象是超类类型,则执行超类的方法。
或者,如果对象属于子类类型,则执行子类的方法。
示例
class Animal {
public void move() {
System.out.println("动物可以移动");
}
}
class Dog extends Animal {
public void move() {
System.out.println("狗可以走路和运行");
}
}
public class TestDog {
public static void main(String args[]) {
Animal a = new Animal(); //对象与动物
Animal b = new Dog(); // Animal reference but Dog object
a.move(); //运行Animal类中的方法
b.move(); //运行Animal类中的方法
}
}输出结果
动物可以移动 狗可以走路和运行