0

Suppose I have class/interface A that is extended/implemented by class B and class C. Class/interface A contains method X. Is there a way to have method X without a body (X();) and so it must be implemented by class B and class C, but not give class B and class C (or any other class except possibly class/interface A) access to each other's method X?

? class/interface A {
  ? X();
}

? class B extends/implements class/interface A {
  @Override
  ? X() {
    ...code...
  }
}

? class C extends/implements class/interface A {
  @Override
  ? X() {
    ...code...
  }
}

I am not sure of modifiers, represented with question marks above, and I am not sure if A should be a class or interface.

EDIT: Additionally, instances of classes B and C are created in class D. The instance of class C in class D is constructed with the instance of class B in class D as a parameter, which is set as a class variable which this instance of class C is constantly getting data from. I do not want this instance of class C to be able to call its class variable object B's method X.

4

1 回答 1

1

如果 B 类和 C 类与 A 类不在同一个包中,则可以X在 A 中创建受保护的抽象。

这意味着您需要将 A 设为抽象而不是接口,因为接口方法始终是公共的。

所以你会有A:

package a.b.c

public abstract class A {
    protected abstract Foo X();
}

在新包中创建 B

package a.b.d

public class B extends a.b.c.A {
    // ... implement X
}

在不同的包中创建 C

package a.b.e

public class C extends a.b.c.A {
    // ... implement X
}

现在,如果您希望类 D 能够调用X,则需要将 D 与 A ie 放在同一个包中a.b.c,但您需要将它们中的每一个都转换A为才能调用X

package a.b.c

public class D {
    public D(a.b.d.B b, a.b.e.C c) {
        // ... call ((A)b).X() or ((A)c).X()
    }
}
于 2018-12-10T02:38:12.677 回答