Tuesday, April 10, 2018

What Is a Class?

In the real world, you'll often find many individual objects all of the same kind. There may be thousands of other bicycles in existence, all of the same make and model. Each bicycle was built from the same set of blueprints and therefore contains the same components. In object-oriented terms, we say that your bicycle is an instance of the class of objects known as bicycles. class is the blueprint from which individual objects are created.
The following Bicycle class is one possible implementation of a bicycle:
class Bicycle {


    int cadence = 0;                            
    int speed = 0;                              STATE OFTHE OBJECT
    int gear = 1;                               



    void changeCadence(int newValue) {          
         cadence = newValue;                    METHOD OF INTERACTION
    }                                           

    void changeGear(int newValue) {             
         gear = newValue;                       METHOD OF INTERACTION
    }                                           

    void speedUp(int increment) {               
         speed = speed + increment;             METHOD OF INTERACTION
    }                                           

    void applyBrakes(int decrement) {           
         speed = speed - decrement;             METHOD OF INTERACTION
    }                                           

    void printStates() {                        
         System.out.println("cadence:" +        
             cadence + " speed:" +              METHOD OF INTERACTION
             speed + " gear:" + gear);          
    }                                           
}

Here's a BicycleDemo class that 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.changeCadence(50);
        bike1.speedUp(10);
        bike1.changeGear(2);
        bike1.printStates();

        bike2.changeCadence(50);
        bike2.speedUp(10);
        bike2.changeGear(2);
        bike2.changeCadence(40);
        bike2.speedUp(10);
        bike2.changeGear(3);
        bike2.printStates();
    }
}

The output of this test prints the ending pedal cadence, speed, and gear for the two bicycles:
cadence:50 speed:10 gear:2
cadence:40 speed:20 gear:3

No comments:

Post a Comment