多态
父类
public class Uncle {
private String name;
private int age;
public void faHongbao() {
System.out.println("舅舅发红包");
}
}
子类一:
public class UncleOne extends Uncle{
public void faHongbao() {
System.out.println("大舅发红包");
}
public void songYan() {
System.out.println("大舅喜欢送烟");
}
}
子类二:
public class UncleTwo extends Uncle{
public void faHongbao() {
System.out.println("二舅发红包");
}
}
多态
UncleOne dajiu = new UncleOne();
dajiu.faHongbao(); // 大舅发红包
UncleTwo uncleTwo = new UncleTwo();
uncleTwo.faHongbao(); // 二舅发红包
向上转型
Uncle dajiu1 = new UncleOne();
dajiu1.faHongbao(); // 大舅发红包
向下转型
Uncle dajiu1 = new UncleOne();
dajiu1.faHongbao();
//dajiu1.songYan(); // 会报错 子类独有的方法在发生向上转型的时候无法在父类中使用
UncleOne temp = (UncleOne) dajiu1; // 向下转型
temp.songYan(); // 可以调用子类独有的方法
instanceof
判断对象是否是指定的类型的实例
避免发生错误的类型转换
public class Demo01 {
public static void main(String[] args) {
//类名 对象名 = new 类名();
Uncle nucle1 = new UncleOne();
if (nucle1 instanceof UncleTwo){
UncleTwo u2 = (UncleTwo) nucle1;
u2.faHongbao();
}
if (nucle1 instanceof UncleOne){
UncleOne u1 = (UncleOne) nucle1;
u1.faHongbao();
u1.chouyan();
}
}
}