Java多态性

多态性:发送消息给某个对象,让该对象自行决定响应何种行为。
      通过将子类对象引用赋值给超类对象引用变量来实现动态方法调用。

      java 的这种机制遵循一个原则:当超类对象引用变量引用子类对象时,被引用对象的类型而不是引用变量的类型决定了调用谁的成员方法,但是这个被调用的方法必须是在超类中定义过的,也就是说被子类覆盖的方法。 

      1. 如果a是类A的一个引用,那么,a可以指向类A的一个实例,或者说指向类A的一个子类。

      2. 如果a是接口A的一个引用,那么,a必须指向实现了接口A的一个类的实例。


//    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 static void main(String[] args) {
        // write your code here


        A a1 = new A();
        A a2 = new B();
        B b = new B();
        C c = new C();
        D d = new D();
//        System.out.println(a1.show(b));
//        System.out.println(a1.show(c));
//        System.out.println(a1.show(d));
        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));
    }

a2.show(b) 结果是 ("B and A");


调用顺序, 依次是this->method(o), super->method(o), this->method(super(o)), super->method(super(o)).

a2的this是B类型。 b 是B类型

1.a2->show(B),在B 中找到show(B).  /// this->method(o),

2.判断超类A中是否定义show(B).  /// this->method(o),

3.未找到show(B) 在A中.  /// super->method(o),

4. 有没有show(A)  ////this->method(super(o)), 

5.有show(A). 但是子类 B覆盖了show(A).

6.所以调用B->SHOW(A)

7.输出为 "B AND A"

 

你可能感兴趣的:(Java多态性)