Here, it says that:
This gives MountainBike all the same fields and methods as Bicycle, yet allows its code to focus exclusively on the features that make it unique. This makes code for your subclasses easy to read. However, you must take care to properly document the state and behavior that each superclass defines, since that code will not appear in the source file of each subclass.
However in my code the inheritance doesn't work properly, probably due to a flaw in my code?
package java1;
class bicycle {
int speed = 0;
int gear = 1;
void accelerate(int incr) {
speed = speed + incr;
}
void decelerate(int incr) {
speed = speed - incr;
}
void changeGear(int val) {
gear = val;
}
void printInfo() {
System.out.println("Speed: " + speed + " Gear: " + gear);
}
}
class mountainbike extends bicycle {
int speed = 10;
}
public class Main {
public static void main(String[] args) {
mountainbike mb1 = new mountainbike();
mb1.accelerate(20);
mb1.accelerate(10);
mb1.printInfo();
}
}
The mountainbike class should inherit all the characteristics of the bicycle class, right? I added a unique property which is int speed = 10
, so starting speed should be 10. However on running the compiler treats starting speed as 0.
Any ideas?