Note that there are some explanatory texts on larger screens.

plurals
  1. POGetting a single instance of an object
    primarykey
    data
    text
    <p>Let's say I have a class <code>A</code> and this class has a List <code>l</code>. There is also a class <code>B</code> that extends <code>A</code> that will access the list <code>l</code>, as shown below. In my program, there must only be an instance of the class <code>B</code> (I'm using Singleton pattern), and there must be only one instance of the List <code>l</code> also, so I'm doing it like this:</p> <pre><code>public abstract class A { protected List&lt;String&gt; l; public A() {} protected synchronized List&lt;String&gt; getList() { if (l == null) l = new LinkedList&lt;String&gt;(); return l; } } //--- public class B extends A { private static B instance; private B() { super(); } public static synchronized B getInstance() { if (instance == null) instance = new B(); return instance; } } </code></pre> <p>What I want to do is:</p> <p>In one instance of <code>B</code>:</p> <pre><code>System.out.println(super.getList().size()); //must print 0 super.getList().add("a"); System.out.println(super.getList().size()); //will print 1 </code></pre> <p>In another instance of <code>B</code>:</p> <pre><code>System.out.println(super.getList().size()); //should print 1, cause i've already //added "a", but prints 0 super.getList().add("b"); System.out.println(super.getList().size()); //should print 2, but prints 1 </code></pre> <p>That is not working as expected though. What am I doing wrong? Can anyone help me?</p> <hr> <p>EDITED:</p> <p>Hi, Bill the Lizard, here are the two classes:</p> <pre><code>public abstract class A { protected static List&lt;String&gt; l; public A() {} protected static synchronized List&lt;String&gt; getList() { if (l == null) l = new LinkedList&lt;String&gt;(); return l; } } //--- public class B extends A { private static B instance; private B() { super(); } public static synchronized B getInstance() { if (instance == null) instance = new B(); return instance; } public void metodo() { System.out.println(super.getList().size()); super.getList().add("a"); System.out.println(super.getList().size()); } } </code></pre> <p>And this is how i create an instance of B:</p> <pre><code>public class ClassTeste { public static void main(String[] args) { B b = B.getInstance(); b.metodo(); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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