在 Java 中从一个实现类中访问两个具有相同接口的变量?
接口在 Java 中类似于类,但是,它仅包含抽象方法和最终且为静态的字段。
你可以使用 Java 中的单个类实现多个接口。只要两个接口具有相同名称,由于接口的所有字段默认情况下都是静态的,所以你可以使用接口名称来访问它们,如下所示 −
示例
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); } }
输出
num field of the interface MyInterface1 100 num field of the interface MyInterface2 1000 num field of the class InterfaceExample 10000
广告