多态
父类
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 chouyan(){
System.out.println("大舅喜欢抽烟");
}
}
子类二:
public class UncleTwo extends Uncle{
public void faHongbao(){
System.out.println("二舅不仅发红包,还送酒");
}
}
启动类
多态
//多态
Uncle uncle1 = new UncleOne();
uncle1.faHongbao();
Uncle uncle2 = new UncleTwo();//向上转型
uncle2.faHongbao();
用父类接受子类的对象,只能调用父类中出现过的方法,子类的扩展的都有方法无法调用
public class Demo {
public static void main(String[] args) {
Uncle uncle1 = new UncleOne();
//uncle1.chouyan(); 不能用
}
向上转型
Uncle uncle2 = new UncleTwo();//向上转型
uncle2.faHongbao();
向下转型
Uncle uncle1 = new UncleOne();
UncleOne u1 = (UncleOne) uncle1;//向下转型
u1.faHongbao();
u1.chouyan();
instanceof
判断对象是否是给定的类的实例
作用:避免类型转换时,出现错误,进而引发程序的崩溃
ublic 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();
}
}
}