Java Classes [Java]

In real life, we know that many objects are similar. For example, every car shares some similarities. We can use a basic blueprint and modify it to make other cars. A class in java is the blueprint you use to make objects. Here is an example:

class Car{

    int speed = 0
    int gear = 1;
    void changeGear(int value) {
         gear = value;
    }

    void speedUp(int amount) { 
         speed = speed + amount; 
    }

    void slowDown(int amount) {
         speed = speed - amount;
    }

    void printInfo() {
         System.out.println("Gear:" + gear + " Speed:" + speed);
    } 

}

In this we setup basic variables and created a few methods to change those variables. The following is a demo class which will create a car object and call the methods to change speed and the gear.

class Demo {
    public static void main(String[] args) {

        // Create car object
        Car myCar = new Car();

        // Call methods
        myCar.speedUp(20);
        myCar.changeGear(1);
        myCar.slowDown(10);
        myCar.printInfo();
    }
}

This will print the following:

Gear: 1 Speed: 10

 

Facebooktwittergoogle_plusredditpinteresttumblrmailFacebooktwittergoogle_plusredditpinteresttumblrmail

Leave a Reply