public class Cat {
public String name;
public void eat(){
System.out.println("Cat.eat()");
}
}
public class YeCat extends Cat{
public int age;
public void eat(){
System.out.println("YeCat.eat()");
}
}
public class HomeCat extends Cat{
public int age;
public void eat(){
System.out.println("HomeCat.eat()");
}
}
public class Main {
public static void main(String[] aaa) {
// 向上转型
Cat yeCat = new YeCat();
// 向上转型可以访问子类重写的方法
yeCat.eat();
// 报错,向上转型不可以访问子类新增的属性和方法
// System.out.println(yeCat.age);
Cat cat = new HomeCat();
// 向下转型
HomeCat homeCat = (HomeCat) cat;
homeCat.eat();
System.out.println(homeCat.age);
}
}
3、instanceof
用来检测某个对象是否是某个类的对象,结果是boolean值
Cat cat = new HomeCat();
// 强转能成功
HomeCat homeCat = (HomeCat) cat;
// 类型强转错误,HomeCat cannot be cast YeCat
YeCat yeCat = (YeCat) cat;
if (cat instanceof HomeCat){
HomeCat home = (HomeCat) cat;
} else if (cat instanceof YeCat){
YeCat ye = (YeCat) cat;
}