I had 2 classes, B
and C
, who needed to keep track of their instances, so each of them has an ArrayList
of their respective types to which instances were added in the constructor.
Since this seemed like common behaviour, I tried to find some sort of standard Java interface or class that expresses this behaviour, something like an InstanceManager
interface. I didn't find any
I ended up trying to write an abstract class for it and I got stuck because I don't know how to specify the specific type of the subclasses. For example:
public abstract class C { public static ArrayList<C> list; }
public class A extends C { }
public class B extends C { }
In this case, B.list
or A.list
would be lists of C
objects, but I would actually want them to be lists of B
and A
objects, respectively.
Is there any way I could make that happen easily?
I am thinking something along the lines of
public abstract class C { public static ArrayList<thisclass> list; }
but that would obviously not work.
I realise that I could probably use generics to handle this, but it feels redundant and I can't help wishing that there is a way to somehow infer the child class type in this situation.
Also, is there any standard Java interface for handling instance management or unique instance id generation?
EDIT:
I have come to understand that static variables are not inherited, and the subclasses' static variables actually refer to the same thing. As such, is there any way I can define instance managing behaviour without resorting to redundancy, having to write the same things in all subclasses?