一维数组的深入,数组中存储的类型为:引用数据类型
对于数组来说,实际上只能存储java对象的“内存地址”。
数组中存储的每一个元素是==“引用”==
示例代码:
public class ArrayTest06 {
public static void main(String[] args) {
int[] s = {1, 2, 3};
for (int i = 0; i < s.length; i++) {
System.out.println(s[i]);
}
// 动态初始化一个长度为2的Animal类型数组。
Animal[] ans = new Animal[2];
// 创建一个Animal对象,放到数组的第一个盒子中。
ans[0] = new Animal();
// Animal数组中只能存放Animal类型,不能存放Product类型。
//ans[1] = new Product();
// Animal数组中可以存放Cat类型的数据,因为Cat是一个Animal。
// Cat是Animal的子类。
ans[1] = new Cat();
System.out.println("============================");
/*Animal a1 = new Animal();
Animal a2 = new Animal();
Animal[] as = {a1,a2};*/
Animal[] as = {new Animal(), new Animal()};// 该数组中存储了两个对象的内存地址。
// 对Animal数组进行遍历
for (int i = 0; i < as.length; i++) {
as[i].move();//调用Animal中的move方法,//这个move()方法不是数组的。是数组当中Animal对象的move()方法。
}
System.out.println("============================");
Cat c1 = new Cat();
Bird b1 = new Bird();
Animal[] ats = {c1, b1};
for (int i = 0; i < ats.length; i++) {
// 这个取出来的可能是Cat,也可能是Bird,不过肯定是一个Animal
// 如果调用的方法是父类中存在的方法不需要向下转型。直接使用父类型引用调用即可。
//ats[i].move();//调用子类中各自重写的方法
//System.out.println("============================");
//调用子类中独有的方法,需要向下转型,强制类型转换
if(ats[i] instanceof Cat){
Cat c2 = (Cat)ats[i];
c1.catchMouse();
}else if(ats[i] instanceof Bird){
Bird b2 = (Bird)ats[i];
b1.sing();
}
}
}
}
class Animal {
public void move() {
System.out.println("动物在移动!");
}
}
class Cat extends Animal {
public void move() {
System.out.println("猫儿在走猫步!");
}
public void catchMouse() {
System.out.println("猫在抓老鼠!");
}
}
class Bird extends Animal {
public void move() {
System.out.println("鸟儿在飞翔!");
}
public void sing() {
System.out.println("鸟儿在歌唱!");
}
}
运行结果:
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/94306.html