- 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
How to call an interface method in Java?
In order to call an interface method from a java program, the program must instantiate the interface implementation program. A method can then be called using the implementation object.
Example
public interface InterfaceDemo{ default public void displayNameDefault(String name){ System.out.println("Your name is : " + name); } public void displayName(String name); public void displayNameAndDesignation(String name, String designation); }
The above interface defines three methods for displaying a name and optionally a job title. One method is a default method that contains implementation logic. The remaining two methods do not include implementation logic.
public class InterfaceDemoImpl implements InterfaceDemo{ public void displayName(String name) { System.out.println(name); } public void displayNameAndDesignation(String name, String designation) { System.out.println("Name:" + name + "\n"+ "Designation:" + designation); } }
The above java program declares that it will implement the interface by using the implements keyword. The program is now obligated to provide java code for the two non-default methods. Accordingly, implementations of the methods are provided.
public class CallInterfaceMethod { public static void main(String args[]){ InterfaceDemo demo = new InterfaceDemoImpl(); demo.displayName("Adithya"); demo.displayNameAndDesignation("Adithya", "Java Developer"); demo.displayNameDefault("Adithya"); } }
The above program instantiates the interface implementation. Next, each of the methods defined in the interface is called.
Output
Adithya Name:Adithya Designation:Java Developer Your name is : Adithya