英文:
Interface reference type
问题
// IBlockSignal.java
public interface IBlockSignal {
public void denySignal();
}
// SpaceTechnology.java
public class SpaceTechnology implements IBlockSignal {
@Override
public void denySignal() {
System.out.println("space-deny");
}
public void spaceOther(){
System.out.println("space-other");
}
}
// Main.java
public class Main {
public static void main(String[] args) {
IBlockSignal ibs;
ibs = new SpaceTechnology();
ibs.denySignal();
System.out.println(ibs.getClass());
// ibs.spaceOther(); // <--- Throws exception. Why? It is of class "SpaceTechnology". And this class does define spaceOther()
((SpaceTechnology) ibs).spaceOther();
}
}
////////////////////////////////////////
// Output:
//
// space-deny
// class SpaceTechnology
// space-other
英文:
While learning about interface reference types I was playing around and found something odd; the code below. As you see, the line with "ibs.spaceOther(); " is confusing me.
Could someone point me in the right direction? Maybe give me a word or something for me to google?
// IBlockSignal.java
public interface IBlockSignal {
public void denySignal();
}
// SpaceTechnology.java
public class SpaceTechnology implements IBlockSignal {
@Override
public void denySignal() {
System.out.println("space-deny");
}
public void spaceOther(){
System.out.println("space-other");
}
}
// Main.java
public class Main {
public static void main(String[] args) {
IBlockSignal ibs;
ibs = new SpaceTechnology();
ibs.denySignal();
System.out.println(ibs.getClass());
// ibs.spaceOther(); // <--- Throws exception. Why? It is of class "SpaceTechnology". And this class does define spaceOther()
((SpaceTechnology) ibs).spaceOther();
}
}
////////////////////////////////////////
// Output:
//
// space-deny
// class SpaceTechnology
// space-other
答案1
得分: 1
ibs.spaceOther()
不会抛出异常。它不会编译。
因为您正在使用接口引用,该引用仅具有左侧类型的方法的访问权限。
链接:https://docs.oracle.com/javase/tutorial/java/IandI/interfaceAsType.html
英文:
ibs.spaceOther()
doesn't throw an exception. It doesn't compile.
Because you are using an interface reference, which only has access to the left-hand side type's methods
https://docs.oracle.com/javase/tutorial/java/IandI/interfaceAsType.html
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论