Monday, November 16, 2009

Basics: Interfaces

An interface is similar to a class, that contains only constants(defined with 'FINAL' keyword), method signatures, and nested types. Methods inside the interface do not have method body. Interfaces can only be implemented by another class or extended by other interfaces, but cannot be instantiated by class objects.

In JAVA, ,multiple inheritance is implemented through interfaces only. That is, a class can extend only one superclass whereas it can implement more than one interface. An interface can extend more than one interface.

Interface Body
o All methods declared in an interface are implicitly public
o All constant values defined in an interface are implicitly pubic,static and final.

When a new interface is defined, it means that a new reference data type is created. This new datatype can be used anywhere when required. A variable defined with this datatype, can be assigned with any object that is an instance of a class that implements the interface. This is done by casting of objects.
Syntax:
    Classname classObject = (Classname)interfaceObject;

Note:
A class that implements an interface must implement all the methods declared in the interface. Hence, care should be taken, so that all the required methods are declared in the interface. Any new methods, required by the interface, should be declared in a new interface which should extend the old interface.

Empty Interfaces, that contain zero methods, can also be used to mark classes. java.lang.Serializable is an example of empty interface.

tutorials

No comments:

Post a Comment