多態(tài)
父類
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ā)紅包欢瞪,還送酒");
}
}
多態(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ò)展的都有方法無法調(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í)例
避免發(fā)生錯(cuò)誤的類型轉(zhuǎn)換
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();
}
}
}