Java多态性例子解释🔚

package com.jasonote.classStudy;

/**
 * Created by Jasonote on 2018/1/18.
 *
 * 类的多态性列子总结
 * 看当前引用类型是谁,调用当前类的方法,如果找不到向下找
 * a,指向子类的父类引用由于向上转型了,它只能访问父类中拥有的方法和属性,而对于子类中存在而父类中不存在的方法,该引用是不能使用的,尽管是重载该方法。
 * b,若子类重写了父类中的某些方法,在调用该些方法的时候,必定是使用子类中定义的这些方法(动态连接、动态调用)
 * c,在继承链中对象方法的调用存在一个优先级:this.show(O)、super.show(O)、this.show((super)O)、super.show((super)O)。即先查this对象的父类,没有就重头再查参数的父类
 */
public class PolymorphicClassDemo {

    public static void main(String[] args) {
        Father father = new Father();
        Father father2 = new Son01();
        Son01 son01 = new Son01();
        Son0101 son0101 = new Son0101();
        Son0102 son0102 = new Son0102();

        //Father And Father
        System.out.println("father.show(father2) ->  " + father.show(father2));

        //Father And Father
        System.out.println("father.show(son0101) ->  " + father.show(son0101));

        //Father And Son0102
        System.out.println("father.show(son0102) ->  " + father.show(son0102));

        //Son01 And Father
        System.out.println("father2.show(son01) ->  " + father2.show(son01));

        //Son01 And Father
        System.out.println("father2.show(son0101) ->  " + father2.show(son0101));

        //Father And Son0102
        System.out.println("father2.show(son0102) ->  " + father2.show(son0102));

        //Son01 And Father
        System.out.println("son01.show(father) ->  " + son01.show(father));

        //Son01 And Father
        System.out.println("son01.show(son0101) ->  " + son01.show(son0101));

        //Father And Son0102
        System.out.println("son01.show(son0102) ->  " + son01.show(son0102));

        //Son01 And Son01
        System.out.println("son01.show(son0102) ->  " + son0101.show(son0101));

    }

}

class Father {
    public String show(Son0102 son0102) {
        return ("Father And Son0102");
    }

    public String show(Father father) {
        return ("Father And Father");
    }

}

class Son01 extends Father {
    public String show(Son01 son01) {
        return ("Son01 And Son01");
    }

    public String show(Father father) {
        return ("Son01 And Father");
    }
}

class Son0101 extends Son01 {

}

class Son0102 extends Son01 {

}

Jason.wang

When you find your talent can't afford to be ambitious, be quiet and study !

You may also like...