Learn programming concepts interactively
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 class - the blueprint for bicycle objectspublic 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 objectspublic class BicycleDemo {public static void main(String[] args) {// Create bicycle objects (instances of the class)Bicycle bike1 = new Bicycle();// Mountain BikeBicycle 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();}}
No operations yet
Start by adding or modifying elements