向上转型与向下转型
public class Test {
public static void main(String[] args) {
show(new Cat()); // 以 Cat 对象调用 show 方法
show(new Dog()); // 以 Dog 对象调用 show 方法
Animal a = new Cat(); // 向上转型
a.eat(); // 调用的是 Cat 的 eat
Cat c = (Cat)a; // 向下转型
c.work(); // 调用的是 Cat 的 work
}
instanceof
public class Test2_instanceof {
public static void main(String[] args) {
Father people = new Son();
//直接类型
boolean b = people instanceof Son;
System.out.println(b);
//强制类型转化
Son son = (Son) people;
Son peoples = new Son();
if(peoples instanceof Father){
System.out.println("peoples是Father的实例");
}else {
System.out.println("peoples不是Father的实例");
}
}
}