简体   繁体   English

Java 在子类中初始化的超类字段

[英]Java superclass field initialised in subclasses

I have a Java superclass with a private field 'variable' and all its subclasses use 'variable' the same way.我有一个带有私有字段“变量”的 Java 超类,它的所有子类都以相同的方式使用“变量”。 Except in every subclass 'variable' gets calculated differently upon initialisation.除了在每个子类中,“变量”在初始化时的计算方式不同。 Where do I best store this field and how do I best initialise it?我在哪里最好存储这个字段以及如何最好地初始化它?

This is my code:这是我的代码:

public abstract class SuperClass {

    private int variable;

    public abstract String getName();

    public void printVariable() { System.out.println(variable); }

    public int squareVariable() { 
        variable *= variable; 
        return variable;
    }

}
public class SubClass1 extends SuperClass {

    private String name;

    public SubClass1(int param) {
        name = "SubClass1";

        super.variable = param + 1;
        // How do I make this better?
    }

    public String getName() { return name; }

}
public class SubClass2 extends SuperClass {

    private String name;

    public SubClass2(int param) {
        name = "SubClass2";

        super.variable = param / 2;
        // How do I make this better?
    }

    public String getName() { return name; }

}

As you can see, right now I use super.variable, but then I have to make 'variable' protected and that approach doesn't seem optimal to me.正如你所看到的,现在我使用 super.variable,但是我必须让“变量”受到保护,这种方法对我来说似乎不是最优的。 What is the right way to do this?这样做的正确方法是什么? Should I define a setter in the superclass?我应该在超类中定义一个 setter 吗? Or can I define a constructor in the superclass which handels this?或者我可以在处理这个的超类中定义一个构造函数吗? Or should I store 'variable' in each subclass separately?或者我应该分别在每个子类中存储“变量”吗? Or should I keep it like this and make 'variable' protected?或者我应该像这样保持它并保护“变量”吗?

First, the code in the question doesn't compile ( The field SuperClass.variable is not visible ), so they are bad examples to being with.首先,问题中的代码无法编译( The field SuperClass.variable is not visible ),因此它们是不好的例子。

Store both variable and name in SuperClass , and initialize them in a constructor.variablename都存储在SuperClass中,并在构造函数中初始化它们。

public abstract class SuperClass {

    private String name;
    private int variable;

    protected SuperClass(String name, int variable) {
        this.name = name;
        this.variable = variable;
    }

    public String getName() { return name; }

    public void printVariable() { System.out.println(variable); }

    public int squareVariable() { 
        variable *= variable; 
        return variable;
    }

}
public class SubClass1 extends SuperClass {

    public SubClass1(int param) {
        super("SubClass1", param + 1);
    }

}
public class SubClass2 extends SuperClass {

    public SubClass2(int param) {
        super("SubClass2", param / 2);
    }

}

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

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