- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Can we declare the method of an Interface final in java?
An interface in Java is a specification of method prototypes. Whenever you need to guide the programmer or, make a contract specifying how the methods and fields of a type should be you can define an interface.
By default, all the methods of an interface are public and abstract. For example, In the following Java program, we are having a declaring a method with name demo.
public interface MyInterface{ void demo(); }
If you compile this using the javac command as shown below −
c:\Examples>javac MyInterface.java
it gets compiled without errors. But, if you verify the interface after compilation using the javap command as shown below −
c:\Examples>javap MyInterface Compiled from "MyInterface.java" public interface MyInterface { public abstract void demo(); }
You can observe that the compiler has placed the public and, abstract modifiers before the method on behalf of you.
In addition to this as of Java9 you can have default, static, private, private and static with the methods of an interface. Except these you cannot use any other modifiers with the methods of an interface.
Moreover, if you declare a method final you cannot override/implement it and, an abstract method must be overridden or implemented. Therefore, you cannot declare the method of an interface final.
If you still do so, it generates a compile time error saying “modifier final not allowed here”.
Example
In the following Java program, we are trying to declare a method of an interface final.
public interface MyInterface{ public abstract final void demo(); }
Compile time error
On compiling, the above program generates the following compile time error −
MyInterface.java:2: error: modifier final not allowed here public abstract final void demo(); ^ 1 error