class Animal {
public void eat() {
System.out.println("吃饱饭");
}
}
class Dog extends Animal {
public void play() {
System.out.println("狗咬人");
}
}
class Worf extends Animal {
public void play() {
System.out.println("狼吃人");
}
}
class Demo1 {
public static void main(String[] args) {
Animal a = new Worf();
System.out.println(a instanceof Dog);
if (a instanceof Dog) {
Dog d = (Dog) (a);
} else {
Worf w = (Worf) (a);
w.play();
}
}
}
Animal a = new Worf();我们之前写这个东西写的很自然这其实是对象的上转型。a instanceof Dog,这个是在问a是Dog类型的吗?Dog d = (Dog) (a);这个就是下转型了。