I am reading a SCJA study guide and it's explaining examples of classes that use inheritance, I saw one example and am confused why the wheelRPM variable is overriden, even with the explanation given below, it inherits the variable so why can't it be set by the methods of the TenSpeedBicycle class? Can anyone help me understand?
// This is the base class, it is a basic bicycle public class Bicycle { private float wheelRPM; private int degreeOfTurn; public void pedalRPM(float pedalRPM) { float gearRatio = 2f; this.wheelRPM = pedalRPM * gearRatio; } public void setDegreeOfTurn(int degreeOfTurn){ this.degreeOfTurn = degreeOfTurn; } public float getWheelRPM() { return this.wheelRPM; } public int getDegreeOfTurn() { return this.degreeOfTurn; } }This is a quote from the book:// This is the subclass, it is a special kind of bicycle. public class TenSpeedBicycle extends Bicycle { private float gearRatio = 2f; private float wheelRPM; // why are we overriding this variable? It is inherited, no? public void setGearRatio(float gearRatio) { this.gearRatio = gearRatio; } public void pedalRPM(float pedalRPM) { this.wheelRPM = pedalRPM * gearRatio; } public float getWheelRPM() { return this.wheelRPM; } }
ok, and to go through what I don't get:The TenSpeedBicycle class, listed in the preceding example, extends the
Bicycle class. This class represents a bicycle that has ten different possible gear
ratios. The regular Bicycle class cannot be used because it has a fixed gear ratio.
The TenSpeedBicycle class adds a method and instance variable so a gear ratio
can be set. It also overrides the wheelRPM variable. This must be done because the
Bicycle class has no setter to set that variable directly. The TenSpeedBicycle
class also overrides the pedalRPM(float pedalRPM) method. In the Bicycle
class version of this method, the gear ratio was fixed. In the newer version, it uses
the gear ratio that can be set. To retrieve the wheelRPM variable, the getter must
also be overridden. This is because the original version of this method can only
return the instance variable that is in its same class.
To which I say, what does 'the Bicycle class has no setter to set that variable directly' have to do with the TenSpeedBicycle class's ability to access the wheelRPM variable, inherited from the Bicycle Class? It has a private access modifier, meaning any Bicycle objects can access their own wheelRPM variables and any TenSpeedBicycle objects created inherit this member that they can access privately too.It also overrides the wheelRPM variable.This must be done because the
Bicycle class has no setter to set that variable directly.