Hi, im really a beginner at java but just trying to understand some basic inheritance theory.

I understand how to make a subclass and make a constructor in the subclass but what i'm confused with is accessing the superclass' private variables.

For example say a subclass has a method which calculates its private variable with a private variable from its superclass. I'm pretty sure:

(superclasses variable)*(subclass variable)

will produce an error with how the superclass variable is private.

I read that getter methods are used to access private variables values from a superclass. I'm just wondering in the subclass' method, how is this done to use these getter methods to get the value I(from superclass private variable) and make the calculation?

Any explainations or examples are much appreciated. I've looked on the net for examples but there either not related to what i'm after or just way to in depth with information which isn't where my java knowledge is yet ^.^

04-20-2010, 03:28 AM

iluxa

Code:

class SuperClass {
private int x;
protected int y;

// getter
public int getX () {
return x;
}
}

class SubClass extends SuperClass {
private int z;

public int calculateStuff () {
return z * y * getX ();
}
}

04-20-2010, 10:58 AM

Tolls

Even better, simply provide an accessor to the private variable, whether protected or public...and final in both cases. "final" because you will almost never want a subclass to be able to overwrite that logic.

The general rule (and as with all general rules, there will be exceptions) is attributes should be inaccessible except via accessors.