An interface in Java is a blueprint of a class. which contains static constants and abstract methods. No concrete method or we can say regular method will be there in the Interface.

To achieve Interface, java provide us a keyword called implements, same like to achieve abstraction in java, we use the keyword extends.

Why we use an interface in java?

  • To achieve total abstraction or 100% abstraction in java.
  • Java doesn’t support multiple inheritance in the case of class, but by using an interface it can achieve multiple inheritance.
  • Interface is also used to achieve loose coupling.

Important points about an Interface

  1. All the methods are public and abstract(as we discussed earlier) And all the fields or variables are public, static, and final, means we must have to initialize the variables inside the interface and that will be final. like
interface Car{
	int row  = 1;  // public + static + final
	void drive(); // public + abstract
}

2. We can’t create an instance of the interface(means interface can’t be instantiated) but we can make the reference of it that refers to the Object of its implementing class.

3. A class can implement more than one interface.

4. An interface can extend to another interface.

5. A class that implements the interface must implement all the methods in the interface. This is most compulsory.

6. It is used to achieve multiple inheritances.

7. It is used to achieve loose coupling.

Program

interface Car {
	
	void brand();  
	
}
class Tesla implements Car{
	
	public void brand(){   
		
		System.out.println("Tesla");
	}
}
class BMWLuxury implements Car{
	
	public void brand(){   
		
		System.out.println("BMWLuxury");
	}
}
class TestInterface{
	
	public static void main(String[] args){
		
		Car cr = new Tesla();
		cr.brand();
		
		Car cr1 = new BMWLuxury();
		cr1.brand();
		
		// we can directly create the object from the class as well like 
		Tesla ts = new Tesla();
		ts.brand();
		
		BMWLuxury bmw = new BMWLuxury();
		bmw.brand();
	}
}

Output:

output interface java

Watch the video below for complete explanation of the above program step by step:

MORE CORE JAVA PROGRAMS