Let’s say I have a class A and this class has a List l. There is also a class B that extends A that will access the list l, as shown below. In my program, there must only be an instance of the class B (I’m using Singleton pattern), and there must be only one instance of the List l also, so I’m doing it like this:
public abstract class A {
protected List<String> l;
public A() {}
protected synchronized List<String> getList() {
if (l == null)
l = new LinkedList<String>();
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;
}
}
What I want to do is:
In one instance of B:
System.out.println(super.getList().size()); //must print 0
super.getList().add("a");
System.out.println(super.getList().size()); //will print 1
In another instance of B:
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
That is not working as expected though. What am I doing wrong? Can anyone help me?
EDITED:
Hi, Bill the Lizard, here are the two classes:
public abstract class A {
protected static List<String> l;
public A() {}
protected static synchronized List<String> getList() {
if (l == null)
l = new LinkedList<String>();
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());
}
}
And this is how i create an instance of B:
public class ClassTeste {
public static void main(String[] args) {
B b = B.getInstance();
b.metodo();
}
}
I’ve run your main revised code, with the following main method,
public static void main(String[] args) { B b1 = B.getInstance(); b1.metodo(); B b2 = B.getInstance(); b2.metodo(); }and got the following output, which matches what you’re looking for