Robotics C++ Physics II AP Physics B Electronics Java Astronomy Other Courses Summer Session  

Interfaces

 

   The primary characteristic of the objects on the following pictures is that they are balls used in different sports.

   Another characteristic they share is that they are round.

   On the other hand, although these balls are used in sport, one made for one sport cannot (or should not) be used in another sport.

   The common characteristics of these objects can be listed in a group like a Java interface. The class could appear as:

 

interface class Ball

{

    //methods common to all types of ball

}

 

This interface would ensure uniformity of terminology but leave it up to subsequent class to specify the specifics of each type of ball.

 

 

 

   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

   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 
{
       void changeCadence(int newValue);   // wheel revolutions per minute

       void changeGear(int newValue);

       void speedUp(int increment);

       void applyBrakes(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 

   // remainder of this class implemented as before

}

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.


Note:

To actually compile the ACMEBicycle class, you'll need to add the public keyword to the beginning of the implemented interface methods.