Home > Java > javaTutorial > How to call interface method in Java?

How to call interface method in Java?

PHPz
Release: 2023-09-04 17:53:04
forward
1775 people have browsed it

How to call interface method in Java?

#In order to call interface methods from a java program, the program must instantiate the interface implementation program. The 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);
}
Copy after login

The above interface defines three methods to display the name and optional job title. One method is the default method that contains the implementation logic. The remaining two methods do not contain 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);
     }
}
Copy after login

The above java program declares that it will use the implements keyword to implement the interface. The program is now obliged to provide java code for these two non-default methods. Accordingly, an implementation of this method is 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");
      }
}
Copy after login

The above program instantiates the interface implementation. Next, each method defined in the interface is called.

Output

Adithya
Name:Adithya
Designation:Java Developer
Your name is : Adithya
Copy after login

The above is the detailed content of How to call interface method in Java?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template