0

我有一个名为 Functions 的接口,其中没有定义任何方法。然后我有一个实现该接口的实现类,并且还有一个在实现类中定义的方法。如果我创建一个接口类型的变量并为其分配一个实现类型的新实例(其中定义了一个方法)。为什么我不能从变量中访问该方法?我想我在这里遗漏了一些东西。我的印象是,如果已经为接口类型的变量分配了一个实现类型的实例,该实例中定义了一个方法,那么该变量可以用于运行该方法。

请指教。先感谢您。

4

4 回答 4

2

从概念上讲,您在这里做错了事。

如果你想调用“那个方法”,那么你应该使用实现类型的变量,而不是接口类型。

或者,如果“那个方法”确实属于接口的预期功能,那么你应该将它“向上”移动到接口。

于 2013-10-17T11:47:44.530 回答
1

据我了解,您的问题如下:

// 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();
于 2013-10-17T11:53:09.877 回答
1

您仅限于由 Reference 类型定义的方法,而不是 Instance 类型,例如:

AutoClosable a = new PrintWriter(...);
a.println( "something" );

这里,AutoClosable 是引用类型,PrintWriter 是实例类型。

此代码将给出编译器错误,因为 AutoClosable 中定义的唯一方法是close().

于 2013-10-17T11:53:42.720 回答
0

你不能这样做,考虑这个例子:

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.
    }
}

因为在编译时,编译器不会知道您正在创建 anew FooBar();并且它有一个调用的方法,该方法testMethod()将动态确定。所以它期望你通过接口变量访问的任何东西都应该在你的接口中可用。

您可以做的是,如果您想通过接口变量访问该方法,最好将该方法移动到接口并让客户端实现它。

如果您对此有疑问,请告诉我。

于 2013-10-17T11:50:50.260 回答