我有四个班级A, B, C and Test
。 Test
用于测试目的。
B
继承自A
。 C
继承自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;
}
}
答案 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();