How to pass reference to abstract class - Java

丶灬走出姿态 提交于 2020-07-19 18:30:12

问题


Data data = new Data("path"); //I read data from excel and save. This code is in Main.

public abstract class Generator{
   public abstract double[][] generate();
   //here I need reference - data
   }

public class GeneratorA extends Generator{
   public double[][] generate(){
   //first implementation - I want to work with data
   }
}


public class GeneratorB extends Generator{
   public double[][] generate(){
   //second implementation - I want to work with data
   }
}

What I need is passing reference (data) to abstract class Generator. I can pass reference in constructors of GeneratorA/GeneratorB but I have more child classes and it is inefficient. Is any way how to pass reference data to abstr. class Generator? I just want to inherit reference from class Generator... Thanks!


回答1:


You must add a constructor to your abstract class. Then you just have to call super(data) in subclasses constructor.

See the code bellow:

public abstract class Generator{

    Data data;

    public Generator(Data data) {
        this.data = data;
    }

    public abstract double[][] generate();
        //here I need reference - data
    }
}

public class GeneratorA extends Generator{

    public GeneratorA(Data data) {
        super(data);
    }

    public double[][] generate(){
        //first implementation - I want to work with data
    }
}


public class GeneratorB extends Generator{

    public GeneratorB(Data data) {
        super(data);
    }

    public double[][] generate(){
    //second implementation - I want to work with data
    }
}



回答2:


An abstract class can have non-abstract methods and constructors.

public abstract class Generator{
   Generator(....)
{
   //set here
}
   public abstract double[][] generate();
   //here I need reference - data
   }

You could use the constructor to set the values in the subclass.

OR

If for some reason you don't want to add a constructor/non-abstract method to the abstract class Generator ,you could add one more class which extends Generator and the other subclasses could extend this new class.

You could write a method in the new class for setting values and use it.




回答3:


It seems from your description you need the same data reference in all Generator objects in this case you can store data as a static field in the abstract class and access in objects of sub classes like:

public abstract class Generator{

    static Data data;
    public static void setData(Data data){
        Generator.data=data;
    }
    public abstract double[][] generate();
}


Data data = new Data("path");
Generator.setData(data);

public class GeneratorA extends Generator{
    public double[][] generate(){
        //here you can work with data..
    }
}


来源:https://stackoverflow.com/questions/36036913/how-to-pass-reference-to-abstract-class-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!