简体   繁体   中英

Class Hierarchy design for optional attribute

At the moment my application has the following class hierarchy:

  • "Class A" is the parent class
  • "Class B" is the child class of "Class A"
  • "Class C" is the child class of "Class A"

At the moment, "Class A" has an attribute called "Attribute D" which is mandatory for "Class B" but optional in "Class C".

May I know the best way to represent this data structure? such that rather than letting others referencing ClassA.getAttributeD without checking if it is NULL, we force them to use Class B and Class C to reference the field

Add a constructor in Class B with Attribute D . In Class C there is just a setter for this attribute.

abstract class A {
   Object attributeD;

   void setAttributeD(Object attributeD) { this.attributeD = attributeD; }
   Object getAttributeD() { return attributeD; }
}

class B extends A {
   B(Object attributeD) { this.attributeD = attributeD; }
}

class C extends A {
}

Don't overuse inheritance. Often it makes things more complicated as necessary. You can see this already in your question.

Take a look at this:

Class A {
    private int d = 1;

    protected int getD() {
        return d;
    }
}

Class B extends A {
    public void doStuff() {
        B b = new B();
        System.out.println(b.getD());  
    }
}

Class C extends A {
    public void doStuff() {
        C c = new C();
        System.out.println(c.getD());  
    }
}

Your main problem is to avoid users accessing attribute D . You can do so by setting attribute D to be private, then declare protected methods to access the attribute. This way, the subclasses will be able to access the attribute.

Make the field in A protected, or keep it private and make its accessor protected.

Thus, users of the class A cannot access the field, but class B and C can use it, and can make accessors public for it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM