Java 判断对象类型instanceof 【多态扩展】

instanceof


public class TestPolymorphism {
public void voice(){
System.out.println("动物叫声!");
}
}
class Cat extends TestPolymorphism{
public void voice(){
System.out.println("喵嗷污!");
}
public void run(){
System.out.println("奔跑吧毛崽子!");
}
}
class Dog extends TestPolymorphism{
public void voice(){
System.out.println("汪汪汪!");
}
}

分隔符--------------------------------------------------------------------------------------------------

public class TestPolymorphism01 {
public static void TestVoice(TestPolymorphism a){
a.voice();
if(a instanceof Cat){
((Cat) a).run();
}

}
public static void main(String[] args){
TestPolymorphism t1=new Cat();
// T1.voice();
TestVoice(t1);
// Cat t2=(Cat)t1;   //instanceof 
// t2.run();//instanceof
}
}


instanceof 判断对象类型

你可能感兴趣的:(Java)