user3002473
user3002473

Reputation: 5074

Java - Can you inherit from a superclass and have a static constructor that references the base classes as opposed to the parent class?

Take a look at the following code

class Parent{
    public static Parent instance = null;
    public Parent(){}
    public static Parent getInstance(){
        if (instance == null)
            instance = new Parent();
        return instance
    }
}

class Child extends Parent{
    public Child(){
        System.out.println("Child initialized.");
    }
}

If I wanted the code to create a static instance in each subclass as well, would I have to copy over the code for getInstance, or does this work?

Upvotes: 0

Views: 46

Answers (1)

regulus
regulus

Reputation: 1622

If I'm not misunderstanding, you want to create a singleton for each subclass and you do not want to repeat the code. If you pass the class of the child to getInstance as parameter that can be possible:

class Parent{
    public static HashMap<Class<? extends Parent>, Parent> instance 
                  = new HashMap<Class<? extends Parent>, Parent>();
    protected Parent(){}
    public static <T> T getInstance(Class<? extends Parent> cls) 
                    throws InstantiationException, IllegalAccessException{
        if (instance.get(cls) == null) {
            instance.put(cls, cls.newInstance());
        }
        return (T)instance.get(cls);
    }
}

class Child extends Parent{
    protected Child(){

    }
}

Child child = Child.getInstance(Child.class);

Upvotes: 1

Related Questions