What is a Class in Java

 What is a Class?

In the real world, we often find many individual objects all of the same kind. In terms of cars,   there may be hundreds of other cards in your town alone .


They may be of the same make and model.

But each car was built from the same set of blueprints. Therefore they contains the same components. 

Let's apply this analogy to bicycles in your town.

In object-oriented concept, we say that any physical  bicycle is an instance of the  of bicycle class. All individual bicycle objects  are created from that blueprint bicycle class.

Here is a one bicycle class 

class Bicycle {

    int speed = 0;

    int gear = 1

    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(speed + " gear:" + gear);

}

}

 The fields speed, and gear represent the object's state, and the methods ( changeGear, speedUp etc.) define its interaction with the outside world.

The Bicycle class needs a  main method to become  a complete application. The main method controls how the program run and create objects

Here the main method  creates two separate Bicycle objects and invokes their methods:

class BicycleDemo {

    public static void main(String[] args) {


        // Create two different 

        // Bicycle objects

        Bicycle bike1 = new Bicycle();

        Bicycle bike2 = new Bicycle();


        // Invoke methods on 

        // those objects

        

        bike1.speedUp(10);

        bike1.changeGear(2);

        bike1.printStates();


        bike2.speedUp(10);

        bike2.changeGear(2);

        bike2.speedUp(10);

        bike2.changeGear(3);

        bike2.printStates();

    }

}

https://youtu.be/N3ObVJrfXPs



https://docs.oracle.com/javase/tutorial/java/concepts/class.html


https://mobile.developer.com/java/data/principles-of-java-class-design.html


Comments