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

How to call interface method in Java?

PHPz
PHPzforward
2023-09-04 17:53:041716browse

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);
}

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);
     }
}

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");
      }
}

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

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete