# 多態(tài)
**父類**
```java
public class Uncle {
public String name ;
private int age ;
public void fahongbao() {
System.out.println("舅舅發(fā)紅包");
}
}
子類一:
public class UncleOne extends Uncle {
public void fahongbao() {
System.out.println("大舅不僅發(fā)紅包還送煙");
}
public void chouyan() {
System.out.println("大舅喜歡抽煙");
}
}
子類二:
public class UncleTwo extends Uncle{
public void fahongbao () {
System.out.println("二舅不僅發(fā)紅包擦剑,還送煙");
}
}
啟動(dòng)類:
多態(tài)
public class Domo {
public static void main(String[] args) {
// 多態(tài)
UncleOne uncle1 = new UncleOne();
uncle1.fahongbao();
UncleTwo uncle2 = new UncleTwo(); // 向上轉(zhuǎn)型
uncle2.fahongbao();
用 父類接受子類的對(duì)象纱兑,只能調(diào)用父類中出現(xiàn)過(guò)的方法稳捆,子類的擴(kuò)展的獨(dú)有方法無(wú)法調(diào)用
public class Domo {
public static void main(String[] args) {
UncleOne uncle1 = new UncleOne();
uncle1.chouyan(); 不能調(diào)用
向上轉(zhuǎn)型
UncleTwo uncle2 = new UncleTwo(); // 向上轉(zhuǎn)型
uncle2.fahongbao();
向下轉(zhuǎn)型
UncleOne uncle1 = new UncleOne();
UncleOne u1 = (UncleOne) uncle1 ; // 向下轉(zhuǎn)型
u1.chouyan();
u1.fahongbao();
instanceof
判斷對(duì)象是否給定的類的實(shí)例
作用:避免類型轉(zhuǎn)換時(shí)鸥印,出現(xiàn)錯(cuò)誤问潭,進(jìn)而引發(fā)程序的崩潰
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();
}
}
}