Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package Inheritance;
- /* What Is an Interface?
- * As you've already learned, objects define their interaction with the
- * outside world through the methods that they expose. Methods form
- * the object's interface with the outside world; the buttons on the front
- * of your television set, for example, are the interface between you
- * and the electrical wiring on the other side of its plastic casing. You
- * press the "power" button to turn the television on and off.
- *
- *
- * In its most common form, an interface is a group of related methods
- * with empty bodies. A bicycle's behavior, if specified as an interface,
- * might appear as follows:
- */
- interface Bicycle
- {
- // wheel revolutions per minute
- void changeCadence (int newValue);
- void changeGear (int newValue);
- void speedUp (int increment);
- void applyBrakers(int decrement);
- }
- /*
- * To implement this interface, the name of your class would change (to
- * a particular brand of bicycle, for example, such as ACMEBicycle),
- * and you'd use the implements keyword in the class declaration:
- */
- class ACMEBicycle implements Bicycle
- {
- int cadence = 0;
- int speed = 0;
- int gear = 1;
- // The compiler will now require that methods
- // changeCadence, changeGear, speedUp, and applyBrakes
- // all be implemented. Compilation will fail if those
- // methods are missing from this class.
- @Override
- public void changeCadence(int newValue)
- {
- cadence = newValue;
- }
- @Override
- public void changeGear(int newValue)
- {
- gear = newValue;
- }
- @Override
- public void speedUp(int increment)
- {
- speed = speed + increment;
- }
- @Override
- public void applyBrakers(int decrement)
- {
- speed = speed - decrement;
- }
- void printState ()
- {
- System.out.println("Cadence : " + cadence);
- System.out.println("Speed : " + speed);
- System.out.println("Gear : " + gear);
- }
- }
- /*
- * Implementing an interface allows a class to become more
- * formal about the behavior it promises to provide.
- * Interfaces form a contract between the class and the
- * outside world, and this contract is enforced at build
- * time by the compiler. If your class claims to implement
- * an interface, all methods defined by that interface must
- * appear in its source code before the class will
- * successfully compile
- */
- public class BicycleDemo
- {
- public static void main(String[] args)
- {
- ACMEBicycle ab1 = new ACMEBicycle();
- ACMEBicycle ab2 = new ACMEBicycle();
- ab1.changeCadence(50);
- ab1.speedUp(10);
- ab1.speedUp(10);
- ab1.changeGear(2);
- ab1.printState();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment