![](/img/trans.png)
[英]In Java, can you call a parent class's superclass constructor through the constructor of the child class of the parent class?
[英]Java - Can you inherit from a superclass and have a static constructor that references the base classes as opposed to the parent class?
看下面的代碼
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.");
}
}
如果我也希望代碼在每個子類中創建一個靜態instance
,是否需要復制代碼以獲取getInstance
,還是可以呢?
如果我沒有誤會,您想為每個子類創建一個單例,並且不想重復代碼。 如果將子類的類作為參數傳遞給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.