在这个用例中如何设计类?

How to design classes in this use case?

我在 java 中有三个 类-A,B,C。条件-

  1. A可以访问B和C的成员
  2. B 可以访问 C 的成员
  3. C 无法访问 A 和 B 的成员
  4. B 无法访问 A 的成员

如果我将 B、C 的成员声明为受保护的并将所有 类 放在一个包中,我将无法执行第三个和第四个条件。 这里的方法应该是什么?

我可以看到大多数答案都提到我可以像 A <- B <- C 那样直接进行继承。但是,让我们假设我们有 类 像 patient 和 doctor。因此,医生需要知道给定患者 ID 的患者的详细信息。明智的实施如果我从患者扩展医生,那将解决用例。但是,从逻辑上讲,将医生从患者扩展到我没有意义,因为医生不是患者。

您应该为每个用例创建适当的接口,而不是使用 类 直接接受接口

例如它可能看起来像

interface AccessibleA {
    int getA();
    void setA(int a);
    // other methods declarations - non accessors
}

interface InaccessibleA {
    // other methods declarations - non accessors
}

class A implements AccessibleA, InaccessibleA {
    private int a;

    // getter and setter

    public A(AccessibleB b, AccessibleC c) {
        // you can assign these values or use them
    }

    // other methods
}

// the same interfaces for B and C

class B implements AccessibleB, InaccessibleB {
    private int b;

    // getter and setter

    public A(InaccessibleA a, AccessibleC c) {
        // you can assign these values or use them
    }

    // other methods
}

// etc

不幸的是,Java 中没有“友元函数”实现(there is something like this in C++),但是有一些方法可以模拟这种行为。例如阅读:

  • Is there a way to simulate the C++ 'friend' concept in Java?

只是我不确定这对你来说是否值得

像这样

package c;
class C { 
    protected String foo;
}

package b;
class B extends C { 
    protected String bar;
}

package a;
class A extends B { 
    protected String baz;
}

受保护字段对不同包中的子类可见,默认(package-private)字段仅对同一包中的子类可见。

documentation

你可以在这里使用继承。 如果C最class为父,则B可以继承C,A可以继承B。 所以在这个场景中,A 可以访问他的父 B 和父的父 C,B 可以访问他的父 C,而 C 不能访问 A 或 B。B 不能访问 A,因为 B 是 A 的父 class。

我想我应该提到我在写问题时正在考虑的确切用例。我稍后相应地更新了我的问题。 对于我的用例,我认为聚合是正确的方法而不是继承,因为 类 具有 has-a 关系而不是 is-a.