roland luo
roland luo

Reputation: 1631

Inherit fields from super class or write fields in sub classes?

So I have the following inheritance structure: Super class A has a bunch of sub classes B,C...Z

And I need to add two fields and their corresponding getters/setters into Some sub classes, say B,C....Q, so approximately half of the sub classes.

My dilemma is, if I add the fields into every sub class, it is very boring and tedious. And it looks smelly because of duplicated code.

But if I add the fields to super class A, It will make the other sub classes from R....Z which don't need the fields having the two fields. I think is redundant.

So which option is better?

Upvotes: 0

Views: 61

Answers (2)

Duncan Jones
Duncan Jones

Reputation: 69339

Create an intermediate class, Foo, which extends A and includes the new fields, plus setters and getters. Have your B,C....Q classes extend Foo rather than A.

A -> Foo -> B
A -> Foo -> C
...
A -> R
A -> S
...

Where X -> Y means X is a superclass of Y

Other answers are mentioning interfaces. I'm assuming you are already grouping your behaviours into meaningful interfaces. This answer addresses how the concrete classes will relate to one another.

Upvotes: 2

snajahi
snajahi

Reputation: 910

According to SOLID principles, and more specifically, the Interface Segregation Principle :

"many client-specific interfaces are better than one general-purpose interface."

So basically create multiple interfaces to represent certain aspects of your domain model and have your classes choose which ones to implement. This way you do not force all your classes to implement methods they do not need.

Example

interface Item{
    String getName();
}

interface Washable{
    void wash();
}

interface Drivable{
    void drive();
}

interface Cookable{
    void cook();
}

class Car implements Item, Washable, Drivable{
    String getName();
    void wash();
    void drive();
}

class Potato implements Item, Washable, Cookable{
    String getName();
    void wash();
    void cook();
}

Upvotes: 1

Related Questions