Interactive Computer Science Tutoring

Learn programming concepts interactively

AHA Schools Logo

What Is a Class?

Learn how classes serve as blueprints for creating objects

Understanding Classes

A class is like a blueprint or template. Just as bicycle manufacturers use the same blueprint to create many bicycles, programmers use classes to create many objects of the same type.

Each bicycle object created from the Bicycle class has its own state (cadence, speed, gear) and can perform the same behaviors (change gear, speed up, brake).

Bicycle Objects (Instances)2 instances
Each bicycle is an instance of the Bicycle class with its own state

Mountain Bike

Selected
Cadence:0 RPM
Speed:0 mph
Gear:1

Road Bike

Cadence:0 RPM
Speed:0 mph
Gear:1
Bicycle Methods
Create New Bicycle
Instantiate a new object from the Bicycle class
Reset Demo
Java Code
Live Java representation with highlighted changes
// Bicycle class - the blueprint for bicycle objects
public class Bicycle {
// Instance variables (state)
int cadence = 0;
int speed = 0;
int gear = 1;
// Methods (behavior)
void changeCadence(int newValue) {
cadence = newValue;
}
void changeGear(int newValue) {
gear = newValue;
}
void speedUp(int increment) {
speed = speed + increment;
}
void applyBrakes(int decrement) {
speed = speed - decrement;
}
void printStates() {
System.out.println("cadence:" + cadence + " speed:" + speed + " gear:" + gear);
}
}
// Demo class showing how to create and use Bicycle objects
public class BicycleDemo {
public static void main(String[] args) {
// Create bicycle objects (instances of the class)
Bicycle bike1 = new Bicycle();
// Mountain Bike
Bicycle bike2 = new Bicycle();
// Road Bike
// Current state of bicycle objects:
// Mountain Bike (bike1):
// cadence: 0, speed: 0, gear: 1
// Road Bike (bike2):
// cadence: 0, speed: 0, gear: 1
// Example method calls:
// bike1.changeCadence(50);
// bike1.speedUp(10);
// bike1.changeGear(2);
// bike1.printStates();
}
}
History0/5
Recent method calls and object operations

No operations yet

Start by adding or modifying elements