扫码一下
查看教程更方便
在上一章中,我们讨论了父类和子类。 如果一个类从它的父类继承了一个方法,那么只要它没有被标记为 final,就可以重写该方法。
重写的好处是:能够定义特定于子类类型的行为,这意味着子类可以根据其要求实现父类方法。
在面向对象的术语中,重写意味着覆盖现有方法的功能。
让我们看一个例子。
class animal { public void move() { system.out.println("animals can move"); } } class dog extends animal { public void move() { system.out.println("dogs can walk and run"); } } public class testdog { public static void main(string args[]) { animal a = new animal(); animal b = new dog(); a.move(); b.move(); } }
编译执行上面的示例,结果如下
animals can move
dogs can walk and run
在上面的示例中,我们可以看到,即使 b 是 animal 类型,它也会运行 dog 类中的 move 方法。 这样做的原因是:在编译时,对引用类型进行检查。 但是,在运行时,jvm 会确定对象类型并运行属于该特定对象的方法。
因此,在上面的示例中,由于 animal 类具有 move 方法,因此程序将正确编译。 然后,在运行时,它运行特定于该对象的方法。
考虑以下示例
class animal { public void move() { system.out.println("animals can move"); } } class dog extends animal { public void move() { system.out.println("dogs can walk and run"); } public void bark() { system.out.println("dogs can bark"); } } public class testdog { public static void main(string args[]) { animal a = new animal(); animal b = new dog(); a.move(); b.move(); b.bark(); } }
上面示例编译执行结果如下
testdog.java:24: error: cannot find symbol
b.bark();
^
symbol: method bark()
location: variable b of type animal
1 error
该程序将抛出编译时错误,因为 b 的引用类型 animal 没有名为 bark 的方法。
当调用重写方法的父类版本时,使用 super 关键字。
class animal { public void move() { system.out.println("animals can move"); } } class dog extends animal { public void move() { super.move(); // 调用父类的方法 system.out.println("dogs can walk and run"); } } public class testdog { public static void main(string args[]) { animal b = new dog(); b.move(); } }
上面示例编译执行结果如下
animals can move
dogs can walk and run