I have a Java superclass with a private field 'variable' and all its subclasses use 'variable' the same way. 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. What is the right way to do this? Should I define a setter in the superclass? 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.
Store both variable
and name
in SuperClass
, and initialize them in a constructor.
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);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.