Tuesday, November 23, 2010

CoolTuts - Java - Interfaces

An interface defines methods that a class implements. In other words, it declares what certain classes do. However an interface itself does nothing. All the action at least, happens inside classes. A class may implement one or more interfaces. This means that the class subscribes to the promises made by those interfaces. Since an interface promises certain methods, a class implementing that interface will need to provide the methods specified by the interface. The methods of an interface are abstract - they have no bodies. Generally a class implementing an interface will not only match the method specifications of the interface, it will also provide bodies - implementations - for its methods.

Example:
interface counting
{
abstract void increment();
abstract int getValue();
}

A class that implements a particular interface must declare this explicitly:
class ScoreCounter implements counting{
....
}
If a class implements an interface, an instance of that class can also be treated as though its type were that interface.

No comments:

Post a Comment