简体   繁体   中英

Subclass inherited field is never used

Can I inherit from a class knowing that some of its fields will never be used?

Let's say I have a Parent class and its subclass Child:

public class Parent {
    private String a;
    private String b;
    private String c;
...
}

public class Child extends Parent {
    private String d;
...
}

Am I allowed to inherit from a class like that knowing that in my Child class I will only use fields "a", "b", "d" and field "c" will never be used?

PS Not asking if compiler is going to complain or not. Asking for a better design practice. If this is bad practice, then how to fix it?

You are asking the wrong question. There may or may not be a problem, but focusing on the data contained in the classes is wrong. You must focus on their behavior.

In her keynote address " Data Abstraction and Hierarchy " Barbara Liskov introduced what is commonly known as the Liskov Substitution Principle , expanded on in the paper " A Behavioral Notion of Subtyping " by Liskov and Jeannette Wing. The idea is that one type is a subtype of another if the subtype could replace the supertype everywhere in a program without impacting its correctness; that is, without breaking it.

What would happen if all Parent instances in your program were replaced with Child instances? Can the child do everything the parent does? Does it support the same operations? Will it produce the same results?

If the answer to that is yes, then Child is a subtype of Parent . If the answer to that is no, then it is not and it should not be a subclass of it. Whether field c is relevant depends entirely on how it is used.

If your Parent class allows being extended and the Child class does not require all the information that its Parent provides, then it is likely your Parent class does too much and it can be separated into different classes .

After you made this refactor, you can extend the class that fits better the behavior you want.

Here is an example of separating the Parent class.

class AB {
    Object a;
    Object b;
}
class ABC extends AB {
    Object c;
}
class ABD extends AB {
    Object d;
}

Inheritance is a poor tool for code reuse, so you may consider composition instead, if these classes have no shared behavior.

class AB {
    Object a;
    Object b;
}
class ABC {
    AB ab;
    Object c;
}
class ABD {
    AB ab;
    Object d;
}

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