Interface Introduction

  • In the Java programming language an interface is an abstract type that is used to specify an interface, that classes must implement.
  • interface keyword used to declare Interfaces, and may only contain method signature and constant declarations (variable declarations that are declared to be both static and final).
  • An interface may never contain method definitions.
  • Interface contains method prototypes (body less methods) and constants.
  • When you create an interface, you're defining a contract for what a class can do, without saying anything about how the class will do it.

Interface Features

  • To reveal an object's programming interface (functionality of the object) without revealing its implementation
  • This is the concept of encapsulation
  • The implementation can change without affecting the caller of the interface
  • The caller does not need the implementation at the compile time
  • It needs only the interface at the compile time
  • During runtime, actual object instance is associated with the interface type
NOTE:
  • You implement an interface by properly and concretely overriding all of the methods defined by the interface.
  • A single class can implement many interfaces.

Example :Simple Interface

interface A 
{ 
	/* internally public static final int x=10;*/
	int x=10; 
	/* convert internally to public abstract void show() */ 
	void show(); 
} 
interface B extends A 
{ 
	/* public abstract void disp(); */ 
	void disp(); 
}

Example :Interface for Multiple Inheritance

interface Animal
{
    void sleep();
    void eat();
}
interface Pet
{
          void faithful();
}
class Dog implements Animal, Pet
{
	public void sleep(){}
	public void eat(){}
	public void faithful(){}
}