数组中存放引用类型分析
程序员文章站
2022-04-15 18:37:03
数组中存放引用类型分析1.代码分析2.程序运行3.结果分析1.代码分析1.源代码:①.main函数内容:public class Test01 {public static void main(String[] args) {Cat c = new Cat();Bird b = new Bird();Animal[] a = { c, b };for (int i = 0; i < a.length; i++) {if (a[i] instanceof C...
1.代码分析
1.源代码:
①.main函数内容:
public class Test01 {
public static void main(String[] args) {
Cat c = new Cat();
Bird b = new Bird();
Animal[] a = { c, b };
for (int i = 0; i < a.length; i++) {
if (a[i] instanceof Cat) {
// 调用子类方法需要强制向下转型
// 不能直接调用会报错
Cat cat = (Cat) a[i];
cat.catchmouse();
} else if (a[i] instanceof Bird) {
Bird bird = (Bird) a[i];
bird.sing();
}
}
}
}
②.所涉及到的类的定义
class Animal {
public void move() {
System.out.println("Animal move..");
}
}
class Cat extends Animal {
public void move() {
System.out.println("cat is walking");
}
public void catchmouse() {
System.out.println("cat can catch mouses");
}
}
class Bird extends Animal {
public void move() {
System.out.println("bird is flying");
}
public void sing() {
System.out.println("bird is sing");
}
}
2.程序运行
cat can catch mouses
bird is sing
3.结果分析
当我们在数组中存放引用数据类型时,想要调用子类的方法,我们需要先
采用instanceof对“对象”进行类型判断,再强制向下转型才可以进行调用。
当我们调用数组中引用的共有方法时,可直接调用,例如:调用a.move()方法
public static void main(String[] args) {
Cat c = new Cat();
Bird b = new Bird();
Animal[] a = { c, b };
for (int i = 0; i < a.length; i++) {
a[i].move();
if (a[i] instanceof Cat) {
// 调用子类方法需要强制向下转型
// 不能直接调用会报错
Cat cat = (Cat) a[i];
cat.catchmouse();
} else if (a[i] instanceof Bird) {
Bird bird = (Bird) a[i];
bird.sing();
}
}
}
程序输出
cat is walking
cat can catch mouses
bird is flying
bird is sing
以上内容仅为个人总结,如有不当欢迎批评指正。
本文地址:https://blog.csdn.net/weixin_46607797/article/details/110237341