0

在接口 ONE 我有一个方法A,在接口 2 我有方法B。这两种方法都在 class 中实现Three。现在我将一个 3 的实例分配给 ONE,但我仍然可以调用BSECOND 的方法吗?

即使这是可能的,它是正确的吗?

4

3 回答 3

5

假设你有这个:

public interface A
{
    public void methodA();
}

public interface B
{
    public void methodB();
}

public class C implements A,B
{
    public void methodA(){...}
    public void methodB(){...}
}

你应该能够做到这一点:

A a = new C();
a.methodA();

但不是这个:

a.methodB()

另一方面,您可以这样做:

B b = new C();
b.methodB();

但不是这个:

b.methodA();

编辑:

这是因为您将 object 定义a为 的实例A。尽管您使用具体类进行初始化 ( new C()),但您正在对接口进行编程,因此只有该接口中定义的方法可见。

于 2013-02-15T14:17:08.907 回答
0

请记住,您只能调用可用于分配的类/接口的方法 - 实际对象支持哪些方法并不重要,就编译器而言,它只查看分配的引用及其具有的方法。

因此,在您的情况下,如果您分配:

Three three = new Three(); // all of the methods in One, Two and Three (if any) can be invoked here
One one = three;    // Only the methods on One can be invoked here
Two two = three;    // Only the methods on Two can be invoked here
于 2013-02-15T14:39:03.937 回答
0

此外,如果Oneextends Two,您将能够做到这一点。这可能不是一个解决方案,但我只是指出另一种方法可以做到这一点。

interface Two
{
void a();
}

interface One extends Two 
{
void b();
}

class Three implements One
{
@Override
public void b() {}

@Override
public void a() {}
}

然后你可以拥有

One one = new Three();
one.a();
one.b();
于 2013-02-15T14:28:57.063 回答