Interface in Java

Interface in Java with Examples

In this article, I am going to discuss Interface in Java with Examples. Please read our previous where we discussed Abstract Class and Abstract Methods in Java with Examples. At the end of this article, you will understand what is Interface in Java is and its need as well as when and how to use the Interfaces in Java with Examples.

Why do we need Interfaces in java?

We know the concept of multiple inheritances where one class is derived from more than one superclass. For example a definition like the below.

Why we need Interface in java

But this concept is not supported by java with classes. Since a large no of real-time applications are required for the use of multiple inheritances where we inherit properties from several different classes. That’s why java provides an alternative approach known as the interface to support the concept of multiple Inheritance.

Note: It can be used to achieve loose coupling. Since methods in interfaces do not have a body, they have to be implemented by the class before you can access them. The class that implements an interface must implement all the methods of that interface. 

What is an interface in Java?

The interface is a fully un-implemented class used for declaring a set of operations of an object. So, you can consider it is a pure abstract class that allows you to define only public static final variables and public abstract methods. In our previous article, we already discussed that abstract method means method without body or implementation. Now, you may have the following question in your mind.

What is the need for the interface when we already have abstract classes to define abstract methods?

Java doesn’t support multiple inheritances with classes. So we must use the interface as a superclass to develop abstraction for supporting multiple inheritances. If we define an abstract class in place of an interface, a service provider cannot implement multiple specifications so the service providers cannot have multiple businesses. If this is not clear at the moment, then don’t worry we will discuss this in detail with an example.

How to declare an interface in Java?

By using the keyword interface you can declare a class type of interface. The syntax is given below.

How to declare an interface in Java

An example is given below.

Java Interface Example

Here the keyword interface tells that Example is an interface containing two final fields such as x and name and one abstract method such as show().

By default, the members of an interface are abstract and final means abstract methods and final fields. Save the above interface in a file We can compile the interface but we cannot execute it because it does not have the main method. Let us check what happens when we compile and execute it

Java Example
     Exception in thread “main” java.lang.NoSuchMethodError: main

Interface Example in Java:

Let us see an example to understand how the interface is used in the java application. Let us first create an interface with the name Shape and then copy and paste the following code into it.

interface Shape 
    public double Area();
    public double Volume();

As you can see, here, we created the interface with two methods (Area and Volume). Now we will create two classes (Cube and Circle) and then we will implement the Shape interface i.e. we will implement the two abstract methods (Cube and Circle) of the Shape interface as shown in the below code.

class Cube implements Shape
    int x = 10;
    public double Area ()
        return (6 * x * x);
    public double Volume ()
        return (x * x * x);

class Circle implements Shape
    int radious = 10;
    public double Area ()
        return (Math.PI * radious * radious);
    public double Volume ()
        return 0;

Now in the main method class, we will create an instance and consume the two methods as shown in the below code.

public class Main
    public static void main (String[]args)
        Shape s1 = new Cube ();
        System.out.println ("The area of Cube is : " + s1.Area ());
        System.out.println ("The volume of Cube is : " + s1.Volume ());
        Shape s2 = new Circle ();
        System.out.println ("The area of Circle is : " + s2.Area ());
        System.out.println ("The volume of Circle is : " + s2.Volume ());

Interface Example

Points to Remember while working with Interfaces in Java:
  1. The interface doesn’t have any superclass/interface
  2. The default access specifier of the interface is the package
  3. Default access specifier of interface member is public
  4. By default, the interface members are public static final variables and public abstract methods. If we don’t provide these keywords compiler places these keywords automatically
How the interface is similar to a class in Java?

An interface is similar to a class in the following ways:

  1. An interface can contain any number of methods like class.
  2. An interface is written in a file with a .java extension, with the name of the interface matching the name of the file.
  3. The byte code of an interface appears in a .class file.
  4. Interfaces appear in packages and their corresponding byte code file must be in a directory structure that matches the package name.
How the interface is different from a class in Java?

An interface is different from a class in the following ways:

  1. We cannot instantiate an interface.
  2. An interface does not contain any constructor.
  3. All of the methods of an interface are abstract.
  4. An interface cannot contain instance fields. The only fields that can appear in an interface must be declared both static and final.
  5. An interface is not extended by a class; it is implemented by a class.
  6. An interface can extend multiple interfaces.
Rules to follow while working with Java Interface:

In developing, using, and deriving a subclass from an interface we must follow the below rules.

  1. The interface cannot have concrete methods, violation leads to CE: interface methods cannot have a body.
  2. In the interface we can have only public static final variables even if we create variables as non-static, non-final variables compiler convert it to the static final variable.
  3. We cannot declare interface members as private or protected members violation leads to CE: “modifier is not allowed here”.
  4. Interface variables should be initialized at the time of creation because they are final else it leads to compile-time error “=expected”.
  5. The interface cannot be instantiated but its reference variable can be created for storing its subclass object reference.
  6. We cannot declare the interface as final it leads to CE: “illegal combination of modifier interface and final”.
  7. The class derived from the interface should implement all abstract methods of interface otherwise it should be declared as abstract else it leads to a compile-time error.
  8. The subclass should implement the interface method with the public keyword because the interface method’s default accessibility modifier is public.
Example to Understand Interfaces in Java:

The following example is to implement multiple inheritances in Java.

class Student
  int roll;
  void getData (int p)
      roll = p;
  void Display ()
      System.out.println ("Roll no is: " + roll);

class Test extends Student
  double p1, p2;
  void PutMarks (double x, double y)
      p1 = x;
      this.p2 = y;
  void ShowMarks ()
      System.out.println ("test1 = " + p1);
      System.out.println ("test2 = " + p2);

interface Sports
    double weight = 50.0;
    void ShowWeight ();

class Results extends Test implements Sports
  double total;
  public void ShowWeight ()
      System.out.println ("Weight = " + weight);
  void DisplayAll()
      total = p1 + p2 + weight;
      Display ();
      ShowMarks ();
      ShowWeight ();
      System.out.println ("The total is : " + total);

public class Main
  public static void main (String[]args)
      Results res = new Results();
      res.PutMarks(55.5, 77.8);

How the interface is different from a class

Relationship Between Classes and Interfaces in Java:

Relationship Between Classes and Interfaces in Java

What are the similarities between interface and abstract class in Java?

An interface is similar to an abstract class in the following ways

  1. Both interface and abstract class cannot be instantiated means we cannot create an object.
  2. But we can create a reference variable for both interface and an abstract class.
  3. The subclass should implement all abstract methods.
  4. Both cannot be declared final.
Difference Between Interface and Abstract Class in Java:

The main difference is to be answered in the interview is as follows

  1. The interface is a fully un-implemented class used for declaring a set of operations of an object.
  2. An abstract class is a partially implemented class. It implements some of the operations of the object those are declared in its interface. These implemented operations are common for all next-level subclasses. The remaining operations are implemented by the next level subclasses according to their requirement.
  3. The interface allows us to develop multiple inheritances. So we must start object design with an interface whereas abstract class does not support multiple inheritances so it always comes next to the interface in the object creation process.
Except above, the following are some of the differences.

Interface in Java

Abstract Class in java

The interface supports Multiple Inheritance. Abstract class does not support Multiple Inheritance.
The interface doesn’t contain Data Members. Abstract class contains Data Members.
The interface doesn’t contain Constructors. Abstract Class contains Constructors.
An interface contains only incomplete members. An abstract class contains both complete and incomplete members.
An interface cannot have access modifiers, by default, everything is assumed as public. An abstract class can have access modifiers for the subs, functions, and properties.
Members of the interface cannot be Static. Only a complete member of the abstract class can be Static.
Should I use public access modifiers for interface methods in Java?

Java interface methods are implicitly public by default, even if they belong to nested interfaces. Non-public modifiers are not valid or necessary for interface methods. So the compiler will fail and warn you in this case. Nested interfaces may be declared protected or private but not the interface methods.

Can an interface extend an abstract class in Java?

No. In java, an interface cannot extend an abstract class. An interface may only extend a super interface. However, an abstract class can implement an interface because an abstract class can contain both abstract methods and concrete methods.

Can an interface be declared as final in Java?

No, it is not permitted to declare an interface as final; it will cause a compilation error. This is a java language design decision. Interface types are intended to be implemented and can be extended without restriction.

Is more than one interface are allowed to implement a class in Java?

Yes, a class can implement multiple interfaces, this is an effective way to achieve multiple inheritances in java. But a class can extend only one superclass.

Is it necessary to implement all interface methods in Java?

It is not necessary for a class that implements an interface to implement all its methods, but in this case, the class must be declared as abstract.

Can an interface variable be overridden in Java?

No, interface variables are constants that cannot be overridden. They are inherited by any class that implements an interface

In the next article, I am going to discuss Composition Aggregation and Association in Java with examples. Here, in this article, I try to explain Interfaces in Java with Examples. I hope you enjoy this Interfaces in Java with Examples article. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *