Can we declare an interface as final in java?


Interface in Java is similar to class but, it contains only abstract methods and fields which are final and static.

Since all the methods are abstract you cannot instantiate it. To use it, you need to implement this interface using a class and provide body to all the abstract methods int it.

Making an interface final.

If you declare a class final cannot extend it. If you make a method final you cannot override it and, if you make a variable final you cannot modify it. i.e. use final with Java entities you cannot modify them further.

If you make an interface final, you cannot implement its methods which defies the very purpose of the interfaces. Therefore, you cannot make an interface final in Java. Still if you try to do so, a compile time exception is generated saying “illegal combination of modifiers − interface and final”.

Example

In the following example we are defining an interface with name MyInterface and using the final modifier with it.

public final interface MyInterface{
   public static final int num = 10;
   public abstract void demo();
}

Compile time error

On compiling, the above program generates the following error

Output

MyInterface.java:1: error: illegal combination of modifiers: interface and final
   public final interface MyInterface{
^
1 error

Updated on: 29-Jun-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements