2021-04-25 多态

# 1

```java
public class Uncle {
    public String name ;
    private  int age ;

    public void fahongbao() {
        System.out.println("舅舅发红包");
    }
}

2

public class UncleOne extends Uncle {
    public  void  fahongbao() {
        System.out.println("大舅不仅发红包还送烟");
    }
    public void chouyan() {
        System.out.println("大舅喜欢抽烟");
    }

}

3

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

}

4

public class Domo {
    public static void main(String[] args) {
        // 多态
        UncleOne uncle1 = new UncleOne();
        // 用父类的类名接受子类创建的对象,只能调用父类中出现过的方法
        uncle1.fahongbao();
      //  uncle1.chouyan(); 不能调用



        UncleOne u1 = (UncleOne) uncle1 ; // 向下转型
        u1.chouyan();
        u1.fahongbao();

        UncleTwo uncle2 = new UncleTwo(); // 向上转型
        uncle2.fahongbao();
    }
}

5

public class Domo01 {
    public static void main(String[] args) {
      // 类名  对象名  = new  类名();
        Uncle uncle1 = new UncleOne();
        if (uncle1 instanceof UncleTwo) {
            UncleTwo u2 = (UncleTwo) uncle1;
            u2.fahongbao();
        }
        if (uncle1 instanceof  UncleOne) {
            UncleOne u1 = (UncleOne) uncle1 ;
            u1.chouyan();
            u1.fahongbao();
        }
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容