instanceofdemo.java
来自「JAVA的一些基础教程」· Java 代码 · 共 45 行
JAVA
45 行
class 动物{
}
class 鸟 extends 动物{
void 唱歌(){
System.out.println("啾啾啾...");
}
}
class 昆虫 extends 动物{
}
class 啄木鸟 extends 鸟{
void 啄木头(){
System.out.println("咚咚咚,啄木头");
}
}
class 蚂蚁 extends 昆虫{
void 拖东西(){
System.out.println("拖树叶");
}
}
public class InstanceofDemo{
public static void 查看动物(动物 a[]){
for(int i=0; i<a.length; i++){
if(a[i] instanceof 鸟){
System.out.println("a["+i+"] 是一只鸟");
// a[i].唱歌();//错误
}
if(a[i] instanceof 昆虫)
System.out.println("a["+i+"] 是一只昆虫");
if(a[i] instanceof 啄木鸟)
System.out.println("a["+i+"] 是一只啄木鸟");
if(a[i] instanceof 蚂蚁)
System.out.println("a["+i+"] 是一只蚂蚁");
}
}
public static void main(String arg[]){
动物 动物园的动物[] = {new 啄木鸟(),new 蚂蚁(),new 鸟(),new 动物()};
查看动物(动物园的动物);
}
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?