# 多态
**父类**
```java
public class Uncle {
public 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 Domo {
public static void main(String[] args) {
// 多态
UncleOne uncle1 = new UncleOne();
uncle1.fahongbao();
UncleTwo uncle2 = new UncleTwo(); // 向上转型
uncle2.fahongbao();
用 父类接受子类的对象,只能调用父类中出现过的方法,子类的扩展的独有方法无法调用
public class Domo {
public static void main(String[] args) {
UncleOne uncle1 = new UncleOne();
uncle1.chouyan(); 不能调用
向上转型
UncleTwo uncle2 = new UncleTwo(); // 向上转型
uncle2.fahongbao();
向下转型
UncleOne uncle1 = new UncleOne();
UncleOne u1 = (UncleOne) uncle1 ; // 向下转型
u1.chouyan();
u1.fahongbao();
instanceof
判断对象是否给定的类的实例
作用:避免类型转换时,出现错误,进而引发程序的崩溃
public class Domo01 {
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.chouyan();
u1.fahongbao();
}
}
}