我们可以在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
因此,您需要将对象引用转换为接口引用。每当您只需要调用接口的方法时。
热门推荐
10 新年门口花束祝福语简短
11 盘锦结婚祝福语大全简短
12 父母生日祝福语 简短独特
13 家庭恩爱祝福语简短英文
14 高考俄语祝福语大全简短
15 虎年祝福语 诗句唯美简短
16 生日婚礼祝福语简短精辟
17 虎年喝酒拜年祝福语简短
18 教师闺蜜祝福语简短