How to call an interface method in Java?

JavaObject Oriented ProgrammingProgramming

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
raja
Published on 28-May-2019 12:23:08
Advertisements