Interface in Java

An Interface contains all abstract methods and defined by interface keyword. The interface is used to achieve complex abstraction in java.

Why use Java interface?

  • It is used to achieve abstraction.

  • By interface, we can support the functionality of multiple inheritances.

  • It can be used to achieve loose coupling.
public interface SocialWorker 
{
public void helpToOthers();
}
public interface RichMan 
{
public void earnMoney();
public void donation();
public void party();
}

One interface inherits another interface. One class may implement multiple interfaces. Keywords implement is used to implement an interface by a class.

public class BusinessMan implements RichMan, SocialWorker {
	……..
}

Interface object can hold references to its implementation class.

RichMan rm =  new BusinessMan();
Rm.donation();
SocialWorker sw = new BusinessMan();
Sw.helpToOthers();

An interface has the following properties :

1. It is similar to the abstract class contains only abstract methods.

2. By default, each attribute is final and static in the interface.

3. By default, each method is public and abstract, so abstract keywords are not required to declare a method.

4. It does not contain constructor.

5. It cannot be instantiated.

6. One interface can inherit multiple interfaces.

7. One class can implement multiple interfaces.

Interfaces are used in the design phase of the project when multiple behaviors from a subsystem are expected.

Java Interface Example

interface Demo{  
void print();  
}  
class Test implements Demo{  
public void print(){System.out.println("interface Demo");}  
  
public static void main(String args[]){  
Test obj = new Test();  
obj.print();  
 }  
}
Example Output

Multiple inheritance in Java by the interface

If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known as multiple inheritances.

Interface in java, Java Interface Example

interface Demo{  
void print();  
}  
interface My{  
void show();  
}  
class Test implements Demo,My{  
public void print(){System.out.println("Hello");}  
public void show(){System.out.println("Java");}  
  
public static void main(String args[]){  
Test obj = new Test();  
obj.print();  
obj.show();  
 }  
}
Example Output

Share