界面引用类型

huangapple go评论85阅读模式
英文:

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

huangapple
  • 本文由 发表于 2020年7月23日 02:12:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/63040652.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定