Sunday 7 June 2015

The Bicycle Example

The Bicycle example is covered in a discussion on Oracle's Java "trails". It touches on the concepts of a software object and inheritance. It also touches on the concepts of "contracts", "interfaces" and "APIs". But I don't go that deep in this code example.

I really just needed a break from arrays. :)

class Bicycle {
        int bikenum = 0;
        int cadence = 0;
        int speed = 0;
        int gear = 1;

        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("Bike:" + bikenum + " Candence:" +
                                cadence + " Speed:" + speed + " Gear:" + gear + "\n");
        }
}

class MountainBike extends Bicycle {
        /* The "extends" keyword will allow MountainBike to inherit
         * all of the attributes of Bicycle. So MountainBike will also
         * have bikenum, cadence, speed, gear and the five methods that
         * were defined.
         */
        boolean frontShocks = true;
        boolean rearShocks = false;

        /* The method "printStates" needs to be redefined as there are
         * two more fields to print.
         */
        void printStates() {
                System.out.println("Bike:" + bikenum + " Front Shocks: " +
                                frontShocks + " Rear Shocks:" + rearShocks +
                                " Candence:" + cadence + " Speed:" + speed +
                                " Gear:" + gear + "\n");
        }
}

public class BicycleDemo {
        public static void main(String[] args) {
                // Create two different Bicycle objects
                Bicycle bike1 = new Bicycle();
                Bicycle bike2 = new Bicycle();
                bike1.bikenum = 1;
                bike2.bikenum = 2;
                bike1.printStates();
                bike2.printStates();

                // 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.changeGear(3);
                bike2.printStates();

                bike1.applyBrakes(3);
                bike1.printStates();

                // Create MountainBike object.
                MountainBike bike3 = new MountainBike();
                bike3.bikenum = 3;
                bike3.printStates();
        }


}

No comments:

Post a Comment

Translate