Accessing variables of two interfaces, which are same from an implementing class in java?

Java 8Object Oriented ProgrammingProgramming

An interface in Java is similar to class but, it contains only abstract methods and fields which are final and static.

You can implement multiple interfaces using a single class in Java. Whenever both interfaces have same name, since all the fields of an interface are static by default, you can access them using the name of the interface as −

Example

interface MyInterface1{
   public static int num = 100;
   public void display();
}
interface MyInterface2{
   public static int num = 1000;
   public void show();
}
public class InterfaceExample implements MyInterface1, MyInterface2{
   public static int num = 10000;
   public void display() {
      System.out.println("This is the implementation of the display method");
   }
   public void show() {
      System.out.println("This is the implementation of the show method");
   }
   public static void main(String args[]) {
      InterfaceExample obj = new InterfaceExample();
      System.out.println("num field of the interface MyInterface1"+MyInterface1.num);
      System.out.println("num field of the interface MyInterface2"+MyInterface2.num);
      System.out.println("num field of the class InterfaceExample "+obj.num);
   }
}

Output

num field of the interface MyInterface1 100
num field of the interface MyInterface2 1000
num field of the class InterfaceExample 10000
raja
Published on 04-Jul-2019 17:05:53
Advertisements