多态

多态

父类

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 chouyan() {
        System.out.println("大舅喜欢抽烟");
    }
}

子类二

public class UncleTwo extends Uncle{
    public void faHongbao(){
        System.out.println("二舅不仅发红包,还送酒");
    }
}

多态

public class Demo {
    public static void main(String[] args) {
        // 多态
        Uncle uncle1 = new UncleOne();
        uncle1.faHongbao();
        Uncle uncle2 = new UncleTwo(); // // 向上转型
        uncle2.faHongbao();

用父类接受子类的对象,只能调用父类中出现过的方法,子类的扩展的都有方法无法调用

public class Demo {
    public static void main(String[] args) {
        Uncle uncle1 = new UncleOne();
        //uncle1.chouyan(); 不能调用

向上转型

Uncle uncle2 = new UncleTwo(); // // 向上转型
uncle2.faHongbao();

向下转型

Uncle uncle1 = new UncleOne();
UncleOne u1 = (UncleOne) uncle1;// 向下转型
        u1.faHongbao();
        u1.chouyan();

instanceof

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

避免发生错误的类型转换
public class Demo01 {
public static void main(String[] args) {
Uncle uncle1 = new UncleOne();
if (uncle1 instanceof UncleTwo){
UncleTwo u2 = (UncleTwo) uncle1;
u2.faHongbao();
}
if (uncle1 instanceof UncleOne) {
UncleOne u1 = (UncleOne) uncle1;
u1.faHongbao();
u1.chouyan();
}
}

}

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