[英]Instance variable of interface type does not have access to implementation class methods where as instance variable of type implementation class do
我有一个称为函数的接口,其中未定义任何方法。 然后,我有一个实现该接口的实现类,并且还有一个在实现类中定义的方法。 如果我创建接口类型的变量,并为其分配实现类型的新实例(其中定义了一个方法)。 为什么不能从变量访问该方法? 我想我在这里错过了一些东西。 我的印象是,如果已为接口类型的变量分配了实现类型的实例,该实例中定义了一个方法,则可以使用该变量来运行该方法。
请指教。 先感谢您。
从概念上讲,您在这里做错了。
如果要调用“那个方法”,则应该使用实现类型的变量,而不是接口类型。
或者,如果“该方法”确实确实属于界面的预期功能,则应将其“向上”移至界面。
据我了解,您的问题如下:
// Interface with no methods
public interface Functions {
}
// Implementation class with a method defined in it
public class Implementation implements Functions {
public void foo() {
System.out.println("Foo");
}
}
public class Main {
public static void main(String[] args) {
// Create a variable from the interface type and
// assign a new instance of the implementation type
Functions f = new Implementation();
// You try to call the function
f.foo(); // This is a compilation error
}
}
这是正确的行为,这是不可能的。 因为编译器看到变量f
具有(静态) Functions
类型,所以它仅看到该接口中定义的函数。 编译器不知道该变量是否实际上包含对Implementation
类实例的引用。
要解决此问题,您要么应该在接口中声明方法
public interface Functions {
public void foo();
}
或使变量具有实现类的类型
Implementation f = new Implementation();
您只能使用“引用”类型而不是“实例”类型定义的方法,例如:
AutoClosable a = new PrintWriter(...);
a.println( "something" );
在这里,AutoClosable是引用类型,而PrintWriter是实例类型。
此代码将给编译器错误,因为AutoClosable中定义的唯一方法是close()
。
您不能这样做,请考虑以下示例:
interface Foo {
}
和类:
class FooBar implements Foo {
public void testMethod() { }
}
class FooBarMain {
public static void main(String[] args) {
Foo foo = new FooBar();
//foo.testMethod(); this won't compile.
}
}
因为在编译时,编译器不会知道您正在创建一个new FooBar();
它有一个称为testMethod()
的方法,该方法将动态确定。 因此,它希望通过接口变量访问的任何内容都应该在您的接口中可用。
您可以做的是,如果要通过接口变量访问该方法,最好将该方法移至接口并让客户端实现。
如果您对此有疑问,请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.