在上一章中,无涯教程讨论了父类和子类。如果一个类从它的父类继承了一个方法,那么只要它没有被标签为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引用Animal对象、 Animal b = new Dog(); //Animal引用Dog对象 a.move(); //运行 Animal 类中的方法 b.move(); //运行 Dog 类中的方法 } }
这将产生以下输出-
链接:https://www.learnfk.comhttps://www.learnfk.com/java/java-overriding.html
来源:LearnFk无涯教程网
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 reference and object Animal b = new Dog(); //Animal reference but Dog object a.move(); //运行 Animal 类中的方法 b.move(); //运行 Dog 类中的方法 b.bark(); } }
这将产生以下输出-
链接:https://www.learnfk.comhttps://www.learnfk.com/java/java-overriding.html
来源:LearnFk无涯教程网
TestDog.java:26: 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(); //Aniaml引用 Dog 对象 b.move(); //运行 Dog 类中的方法 } }
这将产生以下输出-
链接:https://www.learnfk.comhttps://www.learnfk.com/java/java-overriding.html
来源:LearnFk无涯教程网
Animals can move Dogs can walk and run
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)