I made a SuperClass (Abstract), a Subclass (Abstract) and a SubSubClass.
There is a piece of code I want to keep in the constructor of the SuperClass, but it won't work correctly unless I put it the Subclass instead.
The SuperClass:
public abstract class SuperClass{
protected int x, y, halfX, halfY;
public SuperClass(){
halfX = x / 2;
halfY = y / 2;
}
The SubClass:
public abstract class SubClass extends SuperClass{
public SubClass(int x, int y){
this.x = x;
this.y = y;
}
The SubSubClass:
public class SubSubClass extends SubClass{
int half;
public SubSubClass(int x, int y){
super(x, y);
}
public void myMethod(){
half = halfX + halfY;
}
If I remove the halfX = x / 2;
halfY = y / 2;
from the SuperClass constructor and put it into the Subclass constructor, the code works. Like this:
public abstract class SubClass() extends SuperClass{
public SubClass(int x, int y){
this.x = x;
this.y = y;
halfX = x / 2;
halfY = y / 2;
}
}
I want that piece of code available for other subclasses (and subsubclasses) instead of only in that subclass.
Just as you called super(x, y);
in SubSubClass
, you need to do the same thing in SubClass
. There is no magic to it, just pass the values to the SuperClass so that x
and y
will be set before you attempt to calculate half the value.
I highly recommend making your fields final
where ever possible and in this case they should be final
.
BTW: If you want to see what is happening you can step through your code in your debugger.
public abstract class SuperClass{
protected final int x, y, halfX, halfY;
public SuperClass(int x, int y){
this.x = x; // set x before using it.
this.y = y; // set y before using it.
halfX = x / 2;
halfY = y / 2;
}
}
public abstract class SubClass extends SuperClass{
private final int z;
public SubClass(int x, int y, int z){
super(x, y);
// only set fields of SubClass
this.z = z;
}