Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Non static methods are associated with instances of the class, while static methods are associated with class itself. You are trying to access a non static member from static method. So, the compiler cannot associate the non-static member with any object.</p> <p>What you can do is either make both of them static, which you should as you trying to save several instances of <code>Superobject</code> in the list. If you dont make it static, every instance of <code>Superobject</code> will have its own list. OR you can create a separate class and call it <code>SuperobjectCollection</code> and provide methods such as Add, Remove, Get etc to access the underlying List.</p> <p>Consider the following pseudocode</p> <pre><code>class SuperobjectCollection { private List&lt;Superobject&gt; list; public AddObj(Superobject obj) { list.add(obj); } } </code></pre> <p>You can add any logic as you see during adding, retrieving, or removing objects.</p> <p>If you want to keep the list in <code>Superobject</code> class, you have to make it static and access it using static method. If you don't do that (like the code that you have presented), you would have following situation:</p> <pre><code>Class Superobject { int no; int i; String s; List&lt;Superobject&gt; li; } </code></pre> <p>If you create two instances like:</p> <pre><code>Superobject a = new one(); Superobject b = new two(); </code></pre> <p>Both <code>a</code> and <code>b</code> would contain separate <code>li</code>. If your <code>somemethod</code> is non-static you can then access this list in that method like</p> <pre><code>li.add(); </code></pre> <p>or like</p> <pre><code>this.li.add(); </code></pre> <p>Here <code>this</code> is either object <code>a</code> if you called the method like <code>a.somemethod()</code> or <code>b</code> if you called it like <code>b.somemethod()</code></p> <p>Static methods are associate with class not instance, and as such you access it like so:</p> <pre><code>Superobject.someobject(); </code></pre> <p>not like</p> <pre><code>a.someobject(); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload