用Object数组存储不同类型的变量
转载▼
标签:
杂谈
分类: Java
定义一个数组,它可以同时存储不同的类型的元素,看似不可行。但是,因为每个JAVA类都是由Object扩展而来的,因此所有的类都属于Object类型,可以创建一个Object类型的数组来存储任何类型的对象。反过来,对每个数组元素,在instanceof 的帮助下能确定其原来的类型。
下面介绍一个用Object数组来存储一个矩形、一个圆、一个双精度数和一个整数的例子。
package Exercise;
//定义长方形
class Rectangle{
protected double length,width;
Rectangle(double l, double w)
{
this.length = l;
this.width = w;
}
void show()
{
System.out.print("长方形的长为:" + length);
System.out.println(" 长方形的宽为:" + width);
}
}
//定义圆
class Circle2{
protected double r;
Circle2(double r)
{
this.r = r;
}
void show()
{
System.out.println("圆形的半径为:" + r);
}
}
public class ObjectShape {
public static void main(String[] args)
{
Object shape[] = new Object[10];
shape[0] = new Rectangle(2,3);
shape[1] = new Circle2(2); //创建一个Circle类型。
shape[2] = new Integer(3);
shape[3] = new Double(1.0);
for(int i =0;i<4;i++)
{
if((shape[i]) instanceof Circle2)
((Circle2)shape[i]).show();
else if((shape[i]) instanceof Rectangle)
((Rectangle)shape[i]).show();//这里恢复原来的对象类型,用强制类型转换。
else if((shape[i]) instanceof Integer)
System.out.println("整数为:" + shape[i]);
else if((shape[i]) instanceof Double)
System.out.println("浮点数为:" + shape[i]);
}
}
}