简体   繁体   中英

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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM