object数组

用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]);

    

    }

}

}

     


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值