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

sha*_*Hwk 0 java arrays collections

我有四节课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;
}


}
Run Code Online (Sandbox Code Playgroud)

bel*_*lum 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)];
    }
}
Run Code Online (Sandbox Code Playgroud)