【问题标题】:Interface reference type [duplicate]接口引用类型 [重复]
【发布时间】:2020-11-12 09:02:13
【问题描述】:

在学习接口引用类型时,我在玩耍,发现了一些奇怪的东西;下面的代码。如您所见,带有“ibs.spaceOther();”的行让我感到困惑。

有人能指出我正确的方向吗?也许给我一句话或什么让我谷歌?

// 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

【问题讨论】:

  • 编译器只知道ibsIBlockSignal类型,它没有spaceOther方法。 实际(运行时)时间是SpaceTechnology,就编译器而言是巧合。
  • 通过强制转换,你对编译器说“相信我,我知道的比你多,假设这是SpaceTechnology”。

标签: java oop interface


【解决方案1】:

ibs.spaceOther() 不会抛出异常。它无法编译。

因为您使用的是接口引用,它只能访问左侧类型的方法

https://docs.oracle.com/javase/tutorial/java/IandI/interfaceAsType.html

【讨论】:

    猜你喜欢
    • 2016-06-03
    • 2019-01-13
    • 2014-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-15
    • 2014-07-28
    • 1970-01-01
    相关资源
    最近更新 更多