简体   繁体   中英

How can I fill an Arraylist with inner classes?

This is my main class:

import java.util.ArrayList;
public class MainClass {
    public static void main(String[] args){
        ArrayList<SecondClass.InnerClass> list=new ArrayList<SecondClass.InnerClass>();
        list.add(new SecondClass.InnerClass()); //error here (read below)
    }
}       

Here is the second class:

public class SecondClass {
    public class InnerClass{

    }
}

At MainClass , at list.add , I get this error:

No enclosing instance of type SecondClass is accessible. Must qualify the allocation with an enclosing instance of type SecondClass (egxnew A() where x is an instance of SecondClass).

I need to have InnerClass non-static because InnerClass needs to make a static reference to a non-static method. How can I add elements in the ArrayList ?

我认为您需要:

new SecondClass().new InnerClass()

I'd do some reading up on nested classes , and in particular the differences between static and non-static nested classes.

If you choose to make InnerClass a static nested class, note the following:

A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.

This means you don't need an instance of SecondClass in order to make an instance of InnerClass - You can instantiate it as you do at the moment.

If however you make InnerClass a non-static nested class (I believe these are sometimes referred to as inner classes , but double check this terminology), you need to create an instance of SecondClass in order to create an instance of InnerClass :

new SecondClass().new InnerClass()

When you want to use an innerClass you must create an instance of the class it contain innerclass. After that you'll use it. Example how to use an innerclass following the tutorial of Oracle:

SecondClass sc=new SecondClass();
SecondClass.InnerClass in=sc.new InnerClass();

And you can see detail here: http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html

Make InnerClass static

public class SecondClass {
    public static class InnerClass{

    }
}

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