简体   繁体   中英

How do I create an array of references to a class , and store the reference-to values for several other objects in array?

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?

    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();

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()

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM