简体   繁体   English

Java-您可以从超类继承并拥有一个静态构造函数来引用基类而不是父类吗?

[英]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.

相关问题 在Java中,您可以通过父类的子类的构造函数调用父类的超类构造函数吗? - In Java, can you call a parent class's superclass constructor through the constructor of the child class of the parent class? 为什么不能从构造函数是私有的类继承? - Why can you not inherit from a class whose constructor is private? 从 Java 中的父类继承的对象的 ArrayList - ArrayList of Objects That Inherit from Parent Classes in Java Java:一个类可以同时从两个超类继承吗? - Java: Can a class inherit from two super classes at the same time? 在Java中扩展类,但它不会从超类继承属性 - Extending a class in java but it wont inherit properties from the superclass Java 中的通配符,用于从相同 class 继承的类 - WildCard in Java for classes that inherit from same class 一个groovy脚本可以继承Java或Groovy超类吗? - Can a groovy script inherit from a Java or Groovy superclass? 在java中,内部类是否可以从内部类外部类之外定义的抽象类继承? - In java can inner classes inherit from an abstract class defined outside of the inner class's outer class? java,在超类中使用构造函数扩展类 - java, extending class with constructor in superclass 使用@SuperBuilder,我怎样才能让子类也继承其父超类属性? - Using @SuperBuilder, how can I have a subclass also inherit its parent superclass properties?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM