简体   繁体   English

Java:如何使用超类的静态方法从其创建子类的实例

[英]Java: How to Create an instance of a subclass from with a Static method of the super class

My specific problem is that I want to create a static method in a base class which saves away the instances of the subclass in a file. 我的特定问题是我想在基类中创建一个静态方法,该方法将子类的实例保存在文件中。 And another static method in the base class which retrieves the data and recreates the instances of the subclass. 基类中的另一个静态方法将检索数据并重新创建子类的实例。

I have got all of it working except where in my strategy I need to create an instance of the subclass within the static method of the base class. 除了我需要在基类的静态方法中创建子类的实例的策略之外,我已经完成了所有工作。 Please see what I mean below. 请在下面查看我的意思。

And so the general question is in Java how do you Create an instance of a subclass from within a Static method of the superclass. 因此,通常的问题是在Java中,如何从超类的Static方法中创建子类的实例。

class Base

    public static Void saveAllInstances(){
       saveAttributesofAllInstancesInFile();  // this works
    }

    public static Void retrieveAllInstances(){
       destroyAllInstances(); // this works
       getInstanceAttributesFromFile();  // this works and returns e.g. ArrayList<HashMap>

       for( instanceAttributes : retrievedInstances ){

         // Here is the part I cant figure out: I want to create an instance of 
         // the subclass here 
         sub = new Sub();

         sub.setAttributes(instanceAttributes); //this works
       }
}

class Sub extends Base{
}

Apart from the fact that your code isn't valid Java syntax, exactly the way you've done. 除了您的代码不是有效的Java语法之外,这完全是您完成的方式。 However as others have suggested what you're doing is actually probably better suited for a (Pure Fabrication) Factory Pattern. 但是,正如其他人所建议的那样,您实际上正在做的事情实际上可能更适合(纯加工)工厂模式。

Base.java Base.java

public class Base {
    public static void retrieveAllInstances() {
        Sub sub = new Sub();
    }
}

Sub.java 子java

public class Sub extends Base{
}

Works fine. 工作正常。 Apart from the cyclic reference, but if you don't care about maintainability, knock yourself out. 除了循环引用之外,但是如果您不关心可维护性,请淘汰一下自己。

Using the factory pattern works fine. 使用工厂模式可以正常工作。 And looks something like this in pseudocode: 并在伪代码中看起来像这样:

class MainFactory{

    protected Worker makeWorker(){
        return new Worker();
    }

    public createIntanceOfSubworker(){
       Worker i = makeWorker()
    }
}

class SubFactory extends MainFactory{
    @override
    protected SubWorker makeWorker(){
        return new SubWorker();
    }
}

class Worker{
}

class SubWorker extends Worker{
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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