【问题标题】:Java Variables of Interface type接口类型的 Java 变量
【发布时间】:2013-02-04 17:04:35
【问题描述】:

我知道分配给类型为接口的引用变量的对象可能是实现该接口的类的实例。但是对于以下代码块:

public interface foo {
    public abstract void method_1();
}

class bar implements foo {  
    @Overide
    public void method_1() { //Implementation... }

    public void method_2() { //Do some thing... } 
}
.....

foo variable = new bar();
variable.method_1(); // OK;
variable.method_2(); // Is it legal?

是否可以让变量(其声明类型为foo但实际类型为bar)调用接口中未声明的方法_2?提前致谢!

【问题讨论】:

    标签: java interface


    【解决方案1】:

    是的,你可以投射:

    ((bar)variable).method_2();
    

    但您可能不应该这样做。接口的全部意义在于只使用它提供的方法。如果还不够,请不要使用界面。

    【讨论】:

      【解决方案2】:

      variable.method_2() 不会编译,因为 variable 的类型是 foofoo 没有方法 method_2()

      【讨论】:

        【解决方案3】:

        不,不是。如果要访问method_2,则必须将variable 的类型声明为bar

        【讨论】:

          【解决方案4】:

          Is it possible to make the variable (whose declared type is foo but actual type is bar) call the method_2 which is not declared in the interface ?

          这不可能。这将是一个编译时错误。

          您的代码中还有其他标准偏差

          1. 接口和类名应该大写驼峰式(这是 UpperCamelCase)。

          【讨论】:

            【解决方案5】:

            不,这是不合法的。但是,您可以在运行时检查类型并转换为正确的类型:

            if (variable instanceof bar) ((bar)variable).method_2();
            

            (严格来说,您可以在没有instanceof 的情况下进行强制转换,检查您是否确定类型正确,或者如果您错了,很乐意抛出异常。)

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2017-01-02
              • 1970-01-01
              • 2022-01-18
              • 2018-09-22
              • 2021-08-14
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多