Java之Instance关键字

时间:2022-12-04 17:05:02
abstract class Animal
{
abstract void eat();
}
class Dog extends Animal
{
void eat()
{
System.out.println("啃骨头");
}
void lookHome()
{
System.out.println("看家");
}
}
class Cat extends Animal
{
void eat()
{
System.out.println("吃鱼");
}
void catchMouse()
{
System.out.println("抓老鼠");
}
}
class DuotaiDemo
{
public static void main(String[] args)
{
Animal a = new Cat();
method(new Cat());

}
public static void method(Animal a)
{
a.eat();
//instanceof用于判断对象具体类型,只能用于引用类型判断
//通常在向下转型前用于健壮性的判断。
if(a instanceof Cat)
{
Cat c = (Cat)a;
c.catchMouse();
}
}
}