Home > Software design >  How to design classes in this use case?
How to design classes in this use case?

Time:03-16

I have three classes-A,B,C in java. Conditions-

  1. A can access members of B and C
  2. B can access members of C
  3. C cannot access members of A and B
  4. B cannot access members of A

If I declare members of B,C as protected and put all the classes in a package, I won't able to enforce the 3rd and 4th condition. What should be the approach here?

CodePudding user response:

You should create proper interfaces for each usecase and instead of using classes directly accept interfaces

For example it could look like

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

Unfortunately in Java there is not "friend function" implementation (there is something like this in C ) however there are some ways to mock this behaviour. For example read:

Just I'm not sure does it worth in your case

CodePudding user response:

Like this

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

protected fields are visible to subclasses in a different package, default (package-private) fields are only visible to subclasses in the same package.

See the documentation

CodePudding user response:

You can use inheritence here. If C is the parent most class, B can inherit C, and A can inherit B. So in this scenerio, A can access his parent B and parent's parent C, B can access his parent C, While C cannot access A or B. and B cannot access A as B is the parent class of A.

  • Related