Question

public abstract class SuperClass {
    public int x, y;
    public int z = x + y;
}

every subclass of SuperClass should have attributes x, y and z. But while x and y could be different for all subclasses and must therefore manually be initiated, how can I be smart about initiating z? i.e. I don't want to call z = x + y in every subclass of SuperClass.

Was it helpful?

Solution 2

I don't want to call z = x + y in every subclass of SuperClass.

Just give z a default value in your superclass then, e.g. x+y, or leave it blank if you wish. Then in the subclass, define z as you want in the constructor.

public class SuperClass{

int x, y, z;

SuperClass(int x, int y){

    this.x = x;
    this.y = y;

    //pick a default value of z;
    z = x + y;
}

}

public class Example extends SuperClass {

Example(int x, int y){
    super(x , y);

    //pick another z implementation here;
    z = x * y ^ x;
}

}

OTHER TIPS

Make x an y protected or make them avaiable to the sub classes via the appropriate getter and setter methods. Otherwise subclasses won't see them.
To initialize z, you could set it in the the constructor of your SuperClass like:

Superclass(int x, int y)
{
   this.x = x;
   this.y = y;
   this.z = x + y;
}

In your inherited classes then use super(x,y) in their constructor to call the constructor of the SuperClass.

Now that's about initializing them... I don't know, what you want to achieve, but if you want to change x and y so that z is kept consisently as x + y, you have to do that manually. One way to achieve this is to calculate z in the setter methods of x and y.

Edit:
Corresponding setters:

void setX(int x)
{
   this.x = x;
   z = x + y;
}

void setY(int y)
{
   this.y = y;
   z = x + y;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top