将用户定义的对象添加到数组 - 并返回2个对象中的一个

时间:2012-12-03 18:12:16

标签: java arrays collections

我有四个班级A, B, C and TestTest用于测试目的。

B继承自AC继承自A

我在check()类中有一个名为test的方法。它应该返回B or C个对象。所以我希望在数组中添加B and C objects,并在1和2之间调用一个随机数。因此将返回其中一个。我不知道如何将B和C添加到数组中。有人可以告诉我如何用Java做到这一点吗?

public Test{

public A check(){
  // add new B() and new C() to an array
  // call a random number to return element 1 or 2 in the array so it will either return B or C

  return either B or C;
}


}

2 个答案:

答案 0 :(得分:5)

甚至更好:

public class Test{
    private static Random r = new Random();
    private static A[] arr = new A[] {
        new B(), 
        new C()
    };
    public static A check(){
        return arr[r.nextInt(arr.length)];
    }
}

答案 1 :(得分:1)

下面的数组可以包含任何对象

Object[] objects = new Object[2];
objects[0] = new A();
objects[1] = new B();