在Java中,我们可以将对象引用转换为接口引用吗?如果可以,在什么情况下?
是的,可以。
如果您实现了一个接口,并从一个类中为其方法提供了方法体。您可以使用接口的引用变量来保存该类的对象,即,将对象引用转换为接口引用。
但是,使用这种方法只能访问接口的方法,如果尝试访问类的方法,则会生成编译时错误。
示例
在下面的Java示例中,我们有一个名为MyInterface的接口,它包含一个抽象方法display()。
我们有一个名为InterfaceExample的类,它包含一个方法(show())。除此之外,我们还实现了接口的**display()**方法。
在main方法中,我们将类的对象赋值给接口的引用变量,并尝试调用这两个方法。
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
因此,只有当您只需要调用接口的方法时,才需要将对象引用转换为接口引用。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP