
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 Interfaces Have Static Methods in Java?
An interface in Java is similar to class but, it contains only abstract methods and fields which are final and static.
A static method is declared using the static keyword and it will be loaded into the memory along with the class. You can access static methods using class name without instantiation.
Static methods in an interface since java8
Since Java8 you can have static methods in an interface (with body). You need to call them using the name of the interface, just like static methods of a class.
Example
In the following example, we are defining a static method in an interface and accessing it from a class implementing the interface.
interface MyInterface{ public void demo(); public static void display() { System.out.println("This is a static method"); } } public class InterfaceExample{ public void demo() { System.out.println("This is the implementation of the demo method"); } public static void main(String args[]) { InterfaceExample obj = new InterfaceExample(); obj.demo(); MyInterface.display(); } }
Output
This is the implementation of the demo method This is a static method
Advertisements