AppDividend
Latest Code Tutorials

Java Interface Example | Interface in Java Tutorial For Beginners

0

Java Interface Example | Interface in Java Tutorial For Beginners is today’s topic. Java Interface is similar to a class. It is nothing but a collection of abstract methods. In class, multiple inheritance is not possible. To remove this disadvantage, we use an interface which is capable of handling multiple inheritance. An interface can have methods and variables just like the Java class but the difference is that the methods declared in the interface are by default abstract. The variables declared in an interface are public, static & final by default, too.

Why use the interface in Java

Java Interfaces do not have a body; they have to be implemented by the class before you can access them. The class that implements interface must implement all the methods of that interface. Also, the Java programming language does not allow you to extend more than one class. However, you can implement more than one interfaces in your class.

Java Interface Example

If we want to declare an interface, we have to the interface keyword. It is used to provide the total abstraction. That means all the methods in the interface are declared with an empty body and are all the fields are public, static and final by default. A class that implement interface must implement all the methods declared in the interface. If we want to implement an interface, we have to use the implements keyword.

Some important points about Interface

  1. It is a reference type in java.
  2. It has methods, and by default they are abstract.
  3. The data types are public, static and final in an Interface.
  4. We cannot create an object for an interface, i.e., not instantiated.
  5. The interface does not have the constructor.
  6. Whenever a class wants to implement any interface, that class needs to use “implements” keyword instead of “extends.”
  7. An interface cannot implement another Interface. It has to extend another interface if needed.
  8. An interface which is declared inside another interface is referred to as a nested interface.
  9. At the time of declaration, the interface variable must be initialized. Otherwise, the compiler will throw an error.
  10. The class cannot implement two interfaces in java that have methods with the same name but different return type.

Difference between Class and Interface

Class
Interface
In class, you can instantiate the variable and create an object. In an interface, you can’t instantiate variable and create an object.
Class can contain concrete(with implementation) methods. The interface cannot contain concrete(with implementation) methods.
The access specifiers used with classes are private, protected and public. In Interface only one specifier is used- Public.

How to declare an interface

It is the same as declaring a class. We have to use the “interface” keyword instead of class.

Syntax of Java Interface

interface Interface_name
{
   Data types;
   Methods ();
}

How to implement Java Interface

See the following example of Ip.java file.

// AppInterface.java

interface firstInterface
{
  void func();
}
class App implements firstInterface
{
  public void func()
  {
    System.out.println("Implementing interface firstInterface");
  }
}
class AppInterface
{
  public static void main(String []args)
  {
     App app = new App();
     app.func();
  }
}

The output is following.

Java Interface Example

 

This is how a class implements an interface. It has to provide the body of all the methods that are declared in an interface or in other words you can say that class has to implement all the methods of the interface.

See the second example.

interface car
{
  void drive();
}
class Tesla implements car
{
  public void drive()
  {
     System.out.println("Tesla implementing Car Interface");
  }
}
class AppInterface
{
  public static void main(String []args)
  {
     Tesla models = new Tesla();
     models.drive();
  }
}

See the below output.

Interface in Java Tutorial For Beginners

 

Methods in an interface are by default an abstract method. Whenever any class implements an interface then we have to define every method of that interface; otherwise, the class will turn into an abstract class. In that above case drive() is an abstract method in an interface car and it is defined in a Tesla class.

Inheritance in Java Interface

One class extends another class in the same way one interface can extend another interface. Here also extends keyword is used to extend the interface.

Inheritance in Java Interface

 

See the below code example of Java Interface Inheritance.

// Extend.java

interface Printable
{  
    void print();  
}  
interface Showable extends Printable
{  
    void show();  
}  
class Extend implements Showable
{  
	public void print(){System.out.println("Hello");}  
	public void show(){System.out.println("Welcome");}  
  
	public static void main(String args[])
	{  
	    Extend obj = new Extend();  
	    obj.print();  
	    obj.show();  
        }  
}

The output is following.

code example of Java Interface Inheritance

 

Multiple Inheritance by Interface

If the class implements multiple interfaces or the interface extends multiple interfaces, then it is known as Multiple inheritance by the interface in Java.

See the below code example.

// Multi.java

//creating interfaces
interface Printable
{  
	//declaring abstarct method
	void print();
}  
interface Showable
{  
	//declaring abstarct method
	void show(); 
} 
//Multi class implememnting multiple inheritance

class Multi implements Printable,Showable
{  
	//defining methods of interface Printable
	public void print(){System.out.println("App");} 
	
	//defining methods of interface Showable
	public void show(){System.out.println("Dividend");}  
  
	//Driver class
	public static void main(String args[])
	{  
		//creating object
		Multi obj = new Multi();
		//calling print method from printable
		obj.print(); 
		
		//calling show method from showable
		obj.show();  
	}  
}

See the output below.

Multiple Inheritance by Interface in Java

 

Why multiple inheritance is not allowed through class but possible by an interface?

If we use multiple inheritance through the class, it creates ambiguity, but in case of interface, there is no ambiguity.

Let’s this with the help of an example.

// Mul.java
interface X
{
   public void myMethod();
}
//creating interface
interface Y
{
   public void myMethod();
}
// implementing multiple inheritance
class Mul implements X, Y
{
	//defining methods
   public void myMethod()
   {
       System.out.println("Implementing more than one interfaces");
   }
   public static void main(String args[])
   {
	   //creating object
	   Mul obj = new Mul();
	   obj.myMethod();
   }
}

The output is following.

Why multiple inheritance is not allowed through class but possible by an interface?

 

Default Method in Interface: Java 8

After Java 8 there is a Method where we can declare method body in the interface, but for, we need to make the method default.

Let’s see an example of that.

// DefMet.java

interface Drawable
{  
	void draw();  
	default void msg(){System.out.println("default method");}  
}  
class Rectangle implements Drawable
{  
	public void draw(){System.out.println("drawing rectangle");}  
}  
class DefMet
{  
	public static void main(String args[])
	{  
		Drawable d=new Rectangle();  
		d.draw();  
		d.msg();  
	}
}

See the below output.

Default Method in Interface in Java 8

 

Static Method in Interface: Java 8

Since Java 8 we can have a static method in an interface. See the below code.

// StaMet.java

interface Drawable
{  
	void draw(); // abstract method
	static int square(int a){return a*a;} //static method
}  
class Rectangle implements Drawable
{  
	//delaring abstract method
	public void draw(){System.out.println("drawing rectangle");}  
}  
  //Driver class
class StaMet
{  
     public static void main(String args[])
     {  
	Drawable d=new Rectangle();//creating reference variable
	d.draw();
	System.out.println(Drawable.square(3));  
     }
}

See the below output.

Static Method in Interface in Java 8

 

Nested Interface in Java

If an interface is declared within another interface or a class, then the declared interface is known as Nested interface. Nested interfaces are used to group related interface so that these are easy to maintain. The nested interface cannot access directly using the reference of outer class or interface we can access it.

If you are solving a question using a nested interface then you need to remember two crucial points:

  1. The interface must be public if it is declared within another interface, but it can have any access modifier if it is declared within a class.
  2. Nested interfaces are declared implicitly static.

Now, here we’ll discuss two types of nested interface. One nested class which is declared within an interface and another which is declared within a class.

Example of a nested interface within an interface

See the below code.

// NestedInt1.java

//outer interface creating
interface Showable
{  
  void show();
  //nested interface creating within a interface
  interface Welcome
  {  
    void msg();  
  }  
}
//decalring  a class for  accessing nested interface 
class NestedInt1 implements Showable.Welcome
{ 
// defining the method of nested interface 
  public void msg(){System.out.println("Hello,See this is nested interface");}  
  //main method
  public static void main(String args[]) 
  {
	//upcasting  
    Showable.Welcome welcome=new NestedInt1(); //creating reference here 
    welcome.msg();  
  }
}

See the output below.

nested interface within an interface

 

As you can see in the above example accessing the Welcome interface by its outer Showable because it cannot be accessed directly.

In a collection framework, sun microsystem has provided a nested interface Entry. Entry is the subinterface of Map. They are accessed by Map.Entry.

We can imagine it as a box inside another box. We cannot open the outer box without opening another inner box.

Example of the nested interface within a class

Now we will be going to explain about nested interface within a class.

// NestedInt2.java

// creating class
class Outer
{ 
 
// nested interface
  interface Welcome
  {  
     void msg();
  }
}  
 
//accesing the nested interface creating reference 
class NestedInt2 implements Outer.Welcome
{  
     //defining the method of nested class   
    public void msg(){System.out.println("Hello see, this is a nested interface");}  
  
    public static void main(String args[])
    {  
	
        Outer.Welcome welcome=new NestedInt2();//upcasting   
        welcome.msg();  
    }  
}

See the output below.

Example of the nested interface within a class

 

Advantages of Interface

  1. The interface provides a contract for all the implementation classes, so it’s good to code in terms of interfaces because implementation classes can’t remove the methods we are using.
  2. Interfaces are suitable for starting point to define Type and create top level hierarchy in our code.
  3. Since the Java class can implement multiple interfaces, it’s better to use interfaces as the superclass in most of the cases.

See the real-life example.

// RealLife.java

//creating a  interface 
interface Vehicle { 
      
    // all are the abstract methods. 
    void changeGear(int a); 
    void speedUp(int a); 
    void applyBrakes(int a); 
} 
  
class Bike implements Vehicle 
{ 
      
    int speed; 
    int gear; 
      
     //difining a method to change gear
    public void changeGear(int newGear)
    { 
          
        gear = newGear; 
    } 
      
    // defining a method to measure current speed
	
    public void speedUp(int increment)
    {       
        speed = speed + increment; 
    } 
      
    // a method using a break
	
    public void applyBrakes(int decrement)
    { 
          
        speed = speed - decrement; 
    } 
      
    public void printStates() 
    { 
         System.out.println("speed: " + speed + " gear: " + gear); 
    } 
} 
  
class Car implements Vehicle
{ 
      
    int speed; 
    int gear; 
      
    //defining a method to change gear
	
    public void changeGear(int newGear)
    { 
          
        gear = newGear; 
    } 
      
      // defining a method to measure current speed
    public void speedUp(int increment)
    { 
          
        speed = speed + increment; 
    } 
      
    // a method using the break
	
    public void applyBrakes(int decrement)
    { 
          
        speed = speed - decrement; 
    } 
      
    public void printStates() 
    { 
         System.out.println("speed: " + speed + " gear: " + gear); 
    } 
      
} 
class RealLife { 
      
    public static void main (String[] args) { 
      
        // create an instance of Bike 
		
        // performing operations  
        Bike bike = new Bike(); 
        bike.changeGear(1); 
        bike.speedUp(6); 
        bike.applyBrakes(2); 
          
        System.out.println("Bike present state :"); 
        bike.printStates(); 
          
        // creating instance of a car. 
        Car car = new Car(); 
        car.changeGear(2); 
        car.speedUp(7); 
        car.applyBrakes(3); 
          
        System.out.println("car present state :"); 
        car.printStates(); 
    } 
}

See the output below.

Advantages of Java Interface

 

Conclusively, Java Interface Example | Interface in Java Tutorial For Beginners is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.