Creating Simple Classes and Objects in Java


Classes and objects are the foundation of object-oriented programming in Java. Practice creating and using them to model real-world scenarios.

Source Code

class Bicycle {
    int gear;
    int speed;

    public Bicycle(int gear, int speed) {
        this.gear = gear;
        this.speed = speed;
    }

    public void applyBrake(int decrement) {
        speed -= decrement;
    }

    public void speedUp(int increment) {
        speed += increment;
    }
}

public class Test {
    public static void main(String[] args) {
        Bicycle bike = new Bicycle(3, 100);
        System.out.println("Gear: " + bike.gear);
        System.out.println("Speed: " + bike.speed);
        bike.applyBrake(10);
        System.out.println("Speed after brake: " + bike.speed);
    }
}
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments