JAVA多态学习

import javax.xml.ws.Action;

/**
 * @Description: [一句话描述该类的作用]
 * @Author: maxiaoyong
 * @CreateDate: 2018/1/18  14:18
 * @Version: [v1.0]
 */
public class Test1 {
    public static void main(String[] args) {
        A a = new A();
        A ason = new Ason();
        Ason ason1 = new Ason();

        System.out.println("*********A********");
        a.printf(a); 
        a.printf(ason);
        a.printf(ason1);

        System.out.println("*********Ason********");
        ason.printf(a);
        ason.printf(ason);
        ason.printf(ason1);

        System.out.println("*********Ason1********");
        ason1.printf(a);
        ason1.printf(ason);
        ason1.printf(ason1);

    }
}

class A {
    void printf(A a) {
        System.out.println("1 A and A");
    }

    void printf(Ason a) {
        System.out.println("2 A and Ason");
    }
}

class Ason extends A {
    @Override
    void printf(A a) {
        System.out.println("3 Ason and A");
    }

    @Override
    void printf(Ason a) {
        System.out.println("4 Ason and Ason");
    }

}

运行结果:
*********A********
1 A and A
1 A and A
2 A and Ason
*********Ason********
3 Ason and A
3 Ason and A
4 Ason and Ason
*********Ason1********
3 Ason and A
3 Ason and A
4 Ason and Ason
解释和结论:
1.无论方法还是参数都优先子类(注意:调用方的类型和真正new的保持一致,而参数类型是声明的类型)
2.先确定该对象所有的方法(子类包括父类的方法),自子类向父类匹配对应参数的方法,如果参数无匹配,则匹配该参数类型的父类型

You may also like...