标签:关键字 列表 rgs public move 去重 类方法 oid ted
以下内容引用自http://wiki.jikexueyuan.com/project/java/overriding.html:
如果一个类从它的父类继承了一个方法,如果这个方法没有被标记为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 reference and object Animal b = new Dog(); // Animal reference but Dog object a.move();// runs the method in Animal class b.move();//Runs the method in Dog class } } //这将产生如下结果: Animals can move Dogs can walk and run
在上面的例子中,可以看到尽管b是Animal类型,但它运行了dog类的方法。原因是:在编译时会检查引用类型。然而,在运行时,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();// runs the method in Animal class b.move();//Runs the method in Dog class b.bark(); } } //这将产生如下结果: TestDog.java:30: cannot find symbol symbol : method bark() location: class Animal b.bark();
这个程序在编译时将抛出一个错误,因为b的引用类型Animal没有一个名字叫bark的方法。
一、方法重写规则
二、使用super关键字
当调用父类的被重写的方法时,要用关键字super。
class Animal{ public void move(){ System.out.println("Animals can move"); } } class Dog extends Animal{ public void move(){ super.move(); // invokes the super class method System.out.println("Dogs can walk and run"); } } public class TestDog{ public static void main(String args[]){ Animal b = new Dog(); // Animal reference but Dog object b.move(); //Runs the method in Dog class } } //这将产生如下结果: Animals can move Dogs can walk and run
测试工程:https://github.com/easonjim/5_java_example/tree/master/javabasicstest/test18
标签:关键字 列表 rgs public move 去重 类方法 oid ted
原文地址:http://www.cnblogs.com/EasonJim/p/6935738.html