父類:
public class Uncle {
private 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 Demo {
public static void main(String[] args) {
// 多態(tài)
Uncle uncle1 = new UncleOne();
uncle1.faHongbao()
Uncle uncle2 = new UncleTwo(); // // 向上轉(zhuǎn)型
uncle2.faHongbao();
用父類接受子類的對(duì)象耸采,只能調(diào)用父類中出現(xiàn)過的方法兴泥,子類的擴(kuò)展的獨(dú)有方法無法調(diào)用
public class Demo {
public static void main(String[] args) {
Uncle uncle1 = new UncleOne();
// uncle1.chouyan(); 不能調(diào)用
}
向上轉(zhuǎn)型
Uncle uncle2 = new UncleTwo(); // // 向上轉(zhuǎn)型
uncle2.faHongbao();
向下轉(zhuǎn)型
Uncle uncle1 = new UncleOne();
UncleOne u1 = (UncleOne) uncle1; // 向下轉(zhuǎn)型
u1.faHongbao();
u1.chouyan();
instanceof
判斷對(duì)象是否是給定的類的實(shí)例
作用:避免類型轉(zhuǎn)換時(shí),出現(xiàn)錯(cuò)誤虾宇,進(jìn)而引發(fā)程序的崩潰
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();
}
}
}