Interactive Computer Science Tutoring

Learn programming concepts interactively

AHA Schools Logo

What Is Inheritance?

Learn how classes inherit commonly used state and behavior from other classes

Inheritance Concept

Inheritance allows classes to inherit commonly used state and behavior from other classes. Different bike types share bicycle characteristics but add unique features!

Bicycle (Superclass)
MountainBike
RoadBike
TandemBike
Create Bike Instances

Create your first bike instance to see inheritance in action!

Java Inheritance Code
Live Java code showing inheritance hierarchy
// Base class - Bicycle (Superclass)
public class Bicycle {
// Protected fields - accessible by subclasses
protected int speed = 0;
protected int cadence = 0;
protected int gear = 1;
// Constructor
public Bicycle(int startCadence, int startSpeed, int startGear) {
this.cadence = startCadence;
this.speed = startSpeed;
this.gear = startGear;
}
// Methods inherited by all subclasses
public 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 Bicycle
public class MountainBike extends Bicycle {
private boolean hasExtraChainRing;
public MountainBike(int startCadence, int startSpeed, int startGear) {
super(startCadence, startSpeed, startGear); // Call parent constructor
this.hasExtraChainRing = true;
}
// Unique method for MountainBike
public void setExtraChainRing(boolean value) {
hasExtraChainRing = value;
}
}
// Subclass - RoadBike extends Bicycle
public class RoadBike extends Bicycle {
private boolean hasDropHandlebars;
public RoadBike(int startCadence, int startSpeed, int startGear) {
super(startCadence, startSpeed, startGear); // Call parent constructor
this.hasDropHandlebars = true;
}
// Unique method for RoadBike
public void setDropHandlebars(boolean value) {
hasDropHandlebars = value;
}
}
// Subclass - TandemBike extends Bicycle
public 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 TandemBike
public void setNumberOfSeats(int seats) {
numberOfSeats = seats;
}
}
Inheritance Operations0/5
Track inheritance and method calls

No operations yet

Start by adding or modifying elements