Pages

Sunday, February 3, 2013

Basics of Interfaces in Java

To understand Interfaces, I'll start with a simple example to make it easier to grab the concept. Consider an automobiles (Computer controlled robotic cars) to be built for transporting passengers from place to place in the future. Manufacturers write the Java code for operating the automobile i.e., start, stop, turn, accelerate, etc., and electronic instrument managers make systems which receive the GPS information, transmission of traffic conditions which will be used to control the car.
To make this possible, automobile manufacturers have to release a standard methodologies which completely  guide as to how to make the car move and operations related to it. These standard methodologies are the interfaces used by the instrument managers to invoke various methods to command the car. Neither of these two groups knows how exactly the methods are being implemented and they have the right to modify them at any time they want.

Similarly, in Java an interface is a reference type similar to the general classes which contain only constants, method signatures and nested types. Methods in the interfaces cannot have body. Interfaces cannot be instantiated i.e., objects cannot be created for interfaces. Interfaces can be implemented by classes or extended by other interfaces.

Syntax to declare an Interface
public interface InterfaceName {
 // methods here
} 
implements keyword is used to use an interface in our classes and it is done as below :

public class Doggy implements PetClass {
//implementation methods
}
Important Points About Interfaces

  • A reference to the interface can point to the objects of implementing classes of the interface.
  • Every method in an interface is implicitly public and abstract
  • An interface can extend from one or many interfaces using the keyword extends. But a class can only extend one class but implement any number of interfaces.
  • Objects cannot be created for interfaces i.e., interfaces cannot be instantiated.
  • Class implementing the interface must provide functionality to the methods declared in the interface.
Example Program Implementing Interfaces

Save this interface as Pets.java and compile it before compiling the implementing class : http://pastie.org/6033203
Save this implementing class as InterfacesExample.java : http://pastie.org/6033213

Constructors in Interfaces and Implementing Classes :
  • Interfaces CANNOT have constructors because a Constructor CANNOT have a return type but in Interfaces every method SHOULD have a return type (identifier). 
  • Implementing classes can have Constructors as objects can be created and constructors are invoked during the creation of the object itself.
  • Interface only consists of 100% abstract classes and hence there are no more Constructors.

0 comments:

Post a Comment