实现多个接口

时间:2013-02-15 14:10:40

标签: java

在接口ONE中我有方法A,在接口TWO中我有方法B。这两种方法都在类Three中实现。现在我分配一个Three to ONE的实例,但我仍然可以调用SECOND的方法B吗?

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

3 个答案:

答案 0 :(得分: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();

编辑:

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

答案 1 :(得分:0)

如果One延长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();

答案 2 :(得分: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