1.Java实现多态有三个必要条件:继承/实现、重写、向上转型。
2.在Java中有两种形式可以实现多态。继承和接口。
3.注意:(1)java中变量不能重写。(2)多态只针对方法,方法中被private、static、final关键字修饰的又会被关闭多态,同理不能重写。不能重写的东西的调用都是以父类函数为准。
4.经典实例
public class A { public String show(D obj) { return ("A and D"); } public String show(A obj) { return ("A and A"); } } public class B extends A{ public String show(B obj){ return ("B and B"); } public String show(A obj){ return ("B and A"); } } public class C extends B{ } public class D extends B{ } public class Test { public static void main(String[] args) { A a1 = new A(); A a2 = new B(); B b = new B(); C c = new C(); D d = new D(); System.out.println("1--" + a1.show(b)); System.out.println("2--" + a1.show(c)); System.out.println("3--" + a1.show(d)); System.out.println("4--" + a2.show(b)); System.out.println("5--" + a2.show(c)); System.out.println("6--" + a2.show(d)); System.out.println("7--" + b.show(b)); System.out.println("8--" + b.show(c)); System.out.println("9--" + b.show(d)); } }
运行结果:
1--A and A 2--A and A 3--A and D 4--B and A 5--B and A 6--A and D 7--B and B 8--B and B 9--A and D
分析:
从上面的程序中我们可以看出A、B、C、D存在如下关系。