如何创建对类的引用数组,并将其他几个对象的引用值存储在数组中?

时间:2020-12-31 12:18:26

For example, I have this code with these classes. How do i Create an array of references to a class , and store the reference-to values for several other objects like a1 or a2 if created?

例如,我有这些类的代码。如何创建对类的引用数组,并存储其他几个对象(如a1或a2)的引用值(如果已创建)?

    public abstract class Test1 {
    // Instance field vars

    public Test(){
    //initializations
    }

    public void method1(){
    //do's
    }

    @override
    public String toString(){
    return (string content)
    }
}

then I have another similar class

然后我有另一个类似的课

    public class Test2 extends Test1 {
    // Instance field vars

    public Test2(){
    //initializations
    }

    public void method2(){
    //do's
     super.method1();
    }

    @override
    public String toString(){
    return super.toString+(string content)
    }
    }

then, my main is something like this

那么,我的主要是这样的

        Test1 a1 = new Test2()
    System.out.println(a1.toString());
    a1.method1();

2 个解决方案

#1


1  

There is nothing should stop you using ArrayList<Test1>.

没有什么可以阻止你使用ArrayList

List<Test1> myArr = new ArrayList<>();
myArr.add(new Test2());
myArr.get(0);

Or,

 Test1 a1[] = new Test2[10];
   a1[0] = new Test2();

Learn about inheritance to understand super class and subclass relationship.

了解继承以了解超类和子类关系。

#2


1  

How about this: -

这个怎么样: -

Test1 [] arrayOfReferences = new Test1[10];

This can store the 10 references of type Test1 and you can populate the array with all of the concrete implementations of abstract class Test1 like new Test2()

这可以存储类型为Test1的10个引用,并且可以使用抽象类Test1的所有具体实现来填充数组,如新的Test2()

#1


1  

There is nothing should stop you using ArrayList<Test1>.

没有什么可以阻止你使用ArrayList

List<Test1> myArr = new ArrayList<>();
myArr.add(new Test2());
myArr.get(0);

Or,

 Test1 a1[] = new Test2[10];
   a1[0] = new Test2();

Learn about inheritance to understand super class and subclass relationship.

了解继承以了解超类和子类关系。

#2


1  

How about this: -

这个怎么样: -

Test1 [] arrayOfReferences = new Test1[10];

This can store the 10 references of type Test1 and you can populate the array with all of the concrete implementations of abstract class Test1 like new Test2()

这可以存储类型为Test1的10个引用,并且可以使用抽象类Test1的所有具体实现来填充数组,如新的Test2()