```java
//父類
public class Uncle {
private String name;
private int age;
public void faHongbao(){
System.out.println("舅舅發(fā)紅包");
}
}
子類一
public class UncleOne extends Uncle {
public void fangHongbao(){
System.out.println("大舅不僅發(fā)紅包赂摆,還送煙");
}
public void chouyan(){
System.out.println("大舅喜歡抽煙");
}
}
子類二
public class UncleTow extends Uncle {
public void fangHongbao(){
System.out.println("二舅不僅發(fā)紅包昔瞧,還送酒");
}
}
多態(tài)
public class demo {
public static void main(String[] args) {
/* UncleOne uncleOne=new UncleOne();
uncleOne.faHongbao();
UncleTow uncleTow=new UncleTow();
uncleTow.faHongbao();*/
//多態(tài)
Uncle uncle1 = new UncleOne();
uncle1.faHongbao();
Uncle uncle2 = new UncleTow(); //向上轉(zhuǎn)型
uncle2.faHongbao();
}
}
//用父類的類名接受子類創(chuàng)建的對象撮躁,只能調(diào)用父類中出現(xiàn)過的方法
public class demo {
public static void main(String[] args) {
Uncle uncle1 = new UncleOne();
//uncle1,chouyan(); 不能調(diào)用
}
}
Uncle uncle2 = new UncleTow(); //向上轉(zhuǎn)型
uncle2.faHongbao();//大舅發(fā)紅包
Uncle uncle1 = new UncleOne();
UncleOne u1 = (UncleOne) uncle1; //向下轉(zhuǎn)型
u1.fangHongbao();
u1.chouyan;//可以調(diào)用
instanceof
判斷對象是否是給定的類的實例
作用:避免類型轉(zhuǎn)換時,出現(xiàn)錯誤滩褥,進(jìn)而引發(fā)程序的崩潰
public class Demo01 {
public static void main(String[] args) {
Uncle uncle1=new UncleOne();
if(uncle1 instanceof UncleTow){
UncleTow u2= (UncleTow) uncle1;
u2.faHongbao();
}
if(uncle1 instanceof UncleOne){
UncleOne u1= (UncleOne) uncle1;
u1.faHongbao();
u1.chouyan();
}
}
}