Java面向对象三特征——多态

多态

父类
public class Uncle {
    private String name;
    private int age
    public void fahongbao(){
        System.out.println("舅舅发红包");
    }

}
子类一
public class UncleOne  extends Uncle{
    public void fahongbao(){
        System.out.println("大舅发红包");
    }
    public void songYan(){
        System.out.println("大舅喜欢送烟");
    }
}

子类二
public class UncleTwo extends Uncle{
    public void fahongbao(){
        System.out.println("二舅发红包");
    }
}

多态

        UncleOne dajiu = new UncleOne();
        dajiu.fahongbao();// 大舅发红包
        Uncle erjiu = new Uncle();
        erjiu.fahongbao(); // 二舅发红包
向上转型
        Uncle dajiu1 = new Uncle();
        dajiu1.fahongbao();
向下转型
        Uncle dajiu1 = new Uncle();
        dajiu1.fahongbao();
        // 子类独有的方法会无法在父类中使用
        //dajiu1.songYan(); // 会报错
        UncleOne d = (UncleOne) dajiu1;
        d.songYan();

instanceof

判断对象是否是指定的类型的实例

避免发生错误的类型转换

public class Demo2 {
    public static void main(String[] args) {
        Uncle uncle1 = new UncleOne();
        Uncle uncle2 = new UncleTwo();
        if (uncle1 instanceof UncleOne){
            UncleOne u1 = (UncleOne)uncle1;
            u1.fahongbao();
        }
        if(uncle2 instanceof UncleTwo){
            UncleTwo u2 = (UncleTwo)uncle2;
            u2.fahongbao();
        }

    }
}

你可能感兴趣的:(Java面向对象三特征——多态)