Learn programming concepts interactively
Inheritance allows classes to inherit commonly used state and behavior from other classes. Different bike types share bicycle characteristics but add unique features!
Create your first bike instance to see inheritance in action!
// Base class - Bicycle (Superclass)public class Bicycle {// Protected fields - accessible by subclassesprotected int speed = 0;protected int cadence = 0;protected int gear = 1;// Constructorpublic Bicycle(int startCadence, int startSpeed, int startGear) {this.cadence = startCadence;this.speed = startSpeed;this.gear = startGear;}// Methods inherited by all subclassespublic void setCadence(int newValue) {cadence = newValue;}public void setGear(int newValue) {gear = newValue;}public void speedUp(int increment) {speed += increment;}public void brake(int decrement) {speed -= decrement;}}// Subclass - MountainBike extends Bicyclepublic class MountainBike extends Bicycle {private boolean hasExtraChainRing;public MountainBike(int startCadence, int startSpeed, int startGear) {super(startCadence, startSpeed, startGear); // Call parent constructorthis.hasExtraChainRing = true;}// Unique method for MountainBikepublic void setExtraChainRing(boolean value) {hasExtraChainRing = value;}}// Subclass - RoadBike extends Bicyclepublic class RoadBike extends Bicycle {private boolean hasDropHandlebars;public RoadBike(int startCadence, int startSpeed, int startGear) {super(startCadence, startSpeed, startGear); // Call parent constructorthis.hasDropHandlebars = true;}// Unique method for RoadBikepublic void setDropHandlebars(boolean value) {hasDropHandlebars = value;}}// Subclass - TandemBike extends Bicyclepublic class TandemBike extends Bicycle {private int numberOfSeats = 2;public TandemBike(int startCadence, int startSpeed, int startGear) {super(startCadence, startSpeed, startGear); // Call parent constructor}// Unique method for TandemBikepublic void setNumberOfSeats(int seats) {numberOfSeats = seats;}}
No operations yet
Start by adding or modifying elements