有父子继承关系的类,子类重写了父类方法后,会产生多态效果。没有重写不存在多态。
由父类对象指向子类实例,调用子类方法产生多态。
package oop.Demo05; public class B { public void test(){ System.out.println("B=>test() "); } public void run(){ System.out.println("Father run. "); } }
package oop.Demo05; public class A extends B{ @Override public void test() { System.out.println("A=>test() "); } @Override public void run() { System.out.println("Son run. "); } public void eat(){ System.out.println("son eat. "); } }
package oop; import oop.Demo05.A; import oop.Demo05.B; public class Application { public static void main(String[] args) { A a =new A(); //a.test(); a.run(); //a.eat(); B b = new A(); //b.test(); b.run(); //((A) b).eat(); B c = (B) a; //c.test(); c.run(); //((A) c).eat(); B d = new B(); d.run(); } }