```java
//父类
public class Uncle {
private String name;
private int age;
public void faHongbao(){
System.out.println("舅舅发红包");
}
}
子类一
public class UncleOne extends Uncle {
public void fangHongbao(){
System.out.println("大舅不仅发红包,还送烟");
}
public void chouyan(){
System.out.println("大舅喜欢抽烟");
}
}
子类二
public class UncleTow extends Uncle {
public void fangHongbao(){
System.out.println("二舅不仅发红包,还送酒");
}
}
多态
public class demo {
public static void main(String[] args) {
/* UncleOne uncleOne=new UncleOne();
uncleOne.faHongbao();
UncleTow uncleTow=new UncleTow();
uncleTow.faHongbao();*/
//多态
Uncle uncle1 = new UncleOne();
uncle1.faHongbao();
Uncle uncle2 = new UncleTow(); //向上转型
uncle2.faHongbao();
}
}
//用父类的类名接受子类创建的对象,只能调用父类中出现过的方法
public class demo {
public static void main(String[] args) {
Uncle uncle1 = new UncleOne();
//uncle1,chouyan(); 不能调用
}
}
Uncle uncle2 = new UncleTow(); //向上转型
uncle2.faHongbao();//大舅发红包
Uncle uncle1 = new UncleOne();
UncleOne u1 = (UncleOne) uncle1; //向下转型
u1.fangHongbao();
u1.chouyan;//可以调用
instanceof
判断对象是否是给定的类的实例
作用:避免类型转换时,出现错误,进而引发程序的崩溃
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();
}
}
}