数组中存放引用类型分析

数组中存放引用类型分析

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

以上内容仅为个人总结,如有不当欢迎批评指正。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值