Java多态 练习代码

参考链接: https://www.cnblogs.com/chenssy/p/3372798.html

/*多态我们可以总结如下:指向子类的父类引用由于向上转型了,它只能访问父类中拥有的方法和属性,而对于子类中存在而父类中不存在的方法,该引用是不能使用的,尽管子类中的某个方法和父类中方法名一样,参数列表不一样。
    若子类重写了父类中的某些方法,在调用该些方法的时候,必定是使用子类中定义的这些方法(动态连接、动态调用)。*/

/*当超类对象引用变量引用子类对象时,被引用对象的类型而不是引用变量的类型决定了调用谁的成员方法,但是这个被调用的方法必须是在超类中定义过的,也就是说被子类重写的方法。*/

/*当超类对象引用变量引用子类对象时,被引用对象的类型而不是引用变量的类型决定了调用谁的成员方法,但是这个被调用的方法必须是在超类中定义过的,也就是说被子类覆盖的方法。
    这句话对多态进行了一个概括。其实在继承链中对象方法的调用存在一个优先级:this.show(O)、super.show(O)、this.show((super)O)、super.show((super)O)。*/

public class DuotaiTest {
    public static void main(String[] args) {
        GrandFather grandFather1 = new GrandFather();
        GrandFather grandFather2 = new Father();
//        grandFather2.setName("haha");
//
//        System.out.println("name--" + grandFather2.name);
        Father father = new Father();
        Daughter daughter = new Daughter();
        Son son = new Son();
        System.out.println("1--" + grandFather1.show(father));
        System.out.println("2--" + grandFather1.show(daughter));
        System.out.println("3--" + grandFather1.show(son));
        System.out.println("4--" + grandFather2.show(father));
        System.out.println("5--" + grandFather2.show(daughter));
        System.out.println("6--" + grandFather2.show(son));
        System.out.println("7--" + father.show(father));
        System.out.println("8--" + father.show(daughter));
        System.out.println("9--" + father.show(son));
    }
}
 class GrandFather {
//    public String name = "GrandFather";
//
//     public void setName(String s){
//         this.name = s;
//     }
    public String show(Son obj) {return ("GrandFather show Son");}
    public String show(GrandFather obj) {return ("GrandGather show GrandFather");}
}

 class Father extends GrandFather{
//     public String name = "Father";
//     @Override
//     public void setName(String s){
//         this.name = s;
//     }
    public String show(Father obj){return ("Father show Father");}
    @Override
    public String show(GrandFather obj){return ("Father show GrandFather");}
}

 class Daughter extends Father{}

 class Son extends Father{}

结果输出:
1–GrandGather show GrandFather
2–GrandGather show GrandFather
3–GrandFather show Son
4–Father show GrandFather
5–Father show GrandFather
6–GrandFather show Son
7–Father show Father
8–Father show Father
9–GrandFather show Son

你可能感兴趣的:(java杂谈)