我们可以在 Java 中将对象引用转换为接口引用吗?如果可以,什么时候可以?
java 8object oriented programmingprogramming
可以。
如果您实现一个接口并从类中为其方法提供主体。您可以使用接口的引用变量保存该类的对象,即将对象引用转换为接口引用。
但是,使用这种方法您只能访问接口的方法,如果您尝试访问类的方法,则会生成编译时错误。
示例
在下面的 Java 示例中,我们有一个名为 MyInterface 的接口,它有一个抽象方法 display()。
我们有一个名为 InterfaceExample 的类,它有一个方法 (show())。除此之外,我们还实现了接口的 display() 方法。
在主方法中,我们将类的对象分配给接口的引用变量,并尝试调用这两个方法。
interface MyInterface{ public static int num = 100; public void display(); } public class InterfaceExample implements MyInterface{ 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[]) { MyInterface obj = new InterfaceExample(); obj.display(); obj.show(); } }
编译时错误
在编译时,上述程序会产生以下编译时错误 −
InterfaceExample.java:16: error: cannot find symbol obj.show(); ^ symbol: method show() location: variable obj of type MyInterface 1 error
要使此程序正常运行,您需要删除将类的方法调用为 − 的行
示例
interface MyInterface{ public static int num = 100; public void display(); } public class InterfaceExample implements MyInterface{ 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[]) { MyInterface obj = new InterfaceExample(); obj.display(); //obj.show(); } }
现在,程序已成功编译并执行。
输出
This is the implementation of the display method
因此,您需要将对象引用转换为接口引用。每当您需要调用接口的方法时。