public class Test { public static void main (String[] args) { Animal h = new Horse(); h.eat(); } } class Animal { public void eat(){ System.out.println ("Animal is eating."); } } class Horse extends Animal{ public void eat(){ System.out.println ("Horse is eating."); } public void buck(){ } }
一个原则是:使用了什么引用,编译器就会只调用引用类所拥有的方法。如果调用子类特有的方法,如上例的h.buck(); 编译器会抱怨的(编译错误)。也就是说,编译器只看引用类型,而不是对象类型。
下面是有关继承中重写的几个测试
1.函数同等权限,父类引用,子类实例;
public class HelloWorld{ public static void main(String []args){ Animal A = new Horse(); A.eat(); } } class Animal { public void eat() { System.out.println("A is eating"); } } class Horse extends Animal { public void eat() { System.out.println("B is eating"); } }
编译执行
sh-4.3$ javac HelloWorld.java
sh-4.3$ javac HelloWorld.java
sh-4.3$ java -Xmx128M -Xms16M HelloWorld
B is eating
没有问题
2.函数同等权限,子类引用,父类实例
public class HelloWorld{ public static void main(String []args){ //Animal A = new Horse(); Horse A = new Animal(); A.eat(); } } class Animal { public void eat() { System.out.println("A is eating"); } } class Horse extends Animal { public void eat() { System.out.println("B is eating"); } }
编译报错:
sh-4.3$ javac HelloWorld.java
HelloWorld.java:5: error: incompatible types: Animal cannot be converted to Horse
Horse A = new Animal();
^
1 error
向下转型不安全,子类引用不能指向父类对象;
3.函数不同权限,父类引用,子类实例
public class HelloWorld{ public static void main(String []args){ Animal A = new Horse(); //Horse A = new Animal(); A.eat(); } } class Animal { protected void eat() { System.out.println("A is eating"); } } class Horse extends Animal { public void eat() { System.out.println("B is eating"); } }
编译执行
sh-4.3$ javac HelloWorld.java
sh-4.3$ java -Xmx128M -Xms16M HelloWorld
B is eating
没有问题,重写的权限要比父类函数的权限相等或更宽。