多态
父类
public class Uncle {
private String name;
private int aeg;
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 UncleTow extends Uncle{
public void faHongbao() {
System.out.println("二舅发红包");
}
}
多态
public static void main(String[] args) {
// 多态
Uncle uncle1 = new UncleOne();
uncle1.faHongbao();
Uncle uncle2 = new UncleTow(); // // 向上转型
uncle2.faHongbao();
多父类名接受子类创建的对象,只能调用父类出现过的方法,子类的扩展的独有方法无法调用
public static void main(String[] args) {
// 多态
Uncle uncle1 = new UncleOne();
uncle1.faHongbao();
//uncle1.chouyan(); 不能调用
向上转型
Uncle uncle2 = new UncleTow(); // // 向上转型
uncle2.faHongbao();
向下转型
Uncle uncle =new uncleOne;
UncleOne u1 = (UncleOne) uncle1;// 向下转
u1.faHongbao();
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();
}
}
}