[英]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? 如果我也希望代码在每个子类中创建一个静态instance
,是否需要复制代码以获取getInstance
,还是可以呢?
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: 如果将子类的类作为参数传递给getInstance,则可以:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.