关于Java 多态的理解及案例

来源:互联网 发布:收银台软件 编辑:程序博客网 时间:2024/05/17 01:47
package February;public class QQ{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(); /** * 实例化对象 a1: * 此时传入值时,找到对象参数的构造方法调用,当没有对象的方法时,依次寻求值得 本质,即传入值为c时,先找到B,然后才找到A *//** * 实例化对象a2: * A a2 = new B();实例化对象时,A a2存储在栈中,new B();存储在堆中;当调用方法时优先调用对象A中的方法,在A中不存在时在 B中寻求(除了被覆盖 的方法) *//** * 实例化对象b: * 由于继承了A,当B中没有相关方法时,会去A中寻找,如果A中没有的话,会遵循以下优先级原则 *  *//** * 多态机制遵循的原则概括为: * 当超类对象引用变量引用子类对象时,被引用对象的类型而不是引用变量的类型决定了调用谁的成员方法, * 但是这个被调用的方法必须是在超类中定义过的,也就是说被子类覆盖的方法,但是它仍然要根据继承链中方法调用的优先级来确认方法, * 该优先级为:this.show(O)、super.show(O)、this.show((super)O)、super.show((super)O)。 */System.out.println(a1.show(a2));System.out.println(a1.show(b));         System.out.println(a1.show(c));        System.out.println(a1.show(d));        System.out.println(a2.show(a1));System.out.println(a2.show(b));        System.out.println(a2.show(c));        System.out.println(a2.show(d));         System.out.println(b.show(b));        System.out.println(b.show(c));        System.out.println(b.show(d));}} class A  {public String show(D obj){return ("A and D");}public String show(A obj){          return ("A and A");  } public String show(B obj){  return ("B and B");  }  }class B extends A{ public String show(B obj){  return ("B and B");  }      public String show(A obj){             return ("A and B");      }    } class C extends B{}   class D extends B{}  


原创粉丝点击