2013-02-04 161 views
1

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

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,但实际的类型吧)调用未在接口中声明的方法 _2?提前致谢!

回答

2

是的,你可以投:

((bar)variable).method_2(); 

但你可能不应该。接口的要点是只使用它提供的方法。如果它们不够用,那就不要使用界面。

2

variable.method_2()将不编译为variable的类型foofoo没有方法method_2()

2

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

1

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)。
+0

是的,你说得对。谢谢你指出! – Dreamer

1

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

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

(严格说来,你可以投不instanceof检查,如果你肯定知道的类型是正确的,还是很高兴能得到一个异常抛出,如果你错了。)