Access Variables of Two Same Interfaces in Java



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
Updated on: 2020-06-29T14:29:24+05:30

851 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements