Search code examples
javaoopsolid-principles

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?

P.S. 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?


Solution

  • 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.