Saturday, April 16, 2011

JAVA Programming : Interface

JAVA Interface 


Interfaces are declared using the interface keyword and they are like a pure abstract class i.e. every method in an Interface is an abstract method. An interface can not be instantiated they can only be implemented by other classes or can be extended by other interfaces.
Implementing a interface by a class is like making a contract that the class will implement all the methods of that interface. If a class does not implement all the methods of an implemented interface, the Java Compiler will give an error.

Syntax of a Interface:-


[access identifier] interface InterfaceName [extends Interface1, Interface2....]
{
     //adstrace method declarations
}



NOTE: Because all methods in an interface is abstract by definition so their is no need to declare them abstract by using abstract keyword.

Declaring a Interface:-
For example, lets create a interface Record which has three methods add, update and delete.


public interface Record {          
    public void add();
    public void update();
    public void delete();
}



Lets create a class Employee that implements the interface Record. Employee class must implement all the methods of Record interface.


public class Employee implements Record {   

  // fields and methods of class


  // methods of Record interface 
  public void add() {
    // set of java statements 
  }
  public void delete() {
    // set of java statements 
  }
  public void update() {
    // set of java statements   
  }

}



No comments:

Post a Comment