I have a superclass like this, which I expect many classes to inherit:
public abstract class Super { protected Object myField; //Not used anywhere in this class //a load more code here which does useful stuff }
All of these classes will need to use an instance myField. However, the superclass does not. Have I made a bad design decision somewhere?
myField
Not necessary. If all subclasses need the same field for the same reason, then this is no different from providing any other common functions of the base class. as your classes grow, you may find that you add common functions that use this field (for example, referring to it in the equals / hashCode method).
, Object, - , , .
IMHO, , . , , , " X, ( ) X, , , - :
public abstract class Super { protected abstract Object getMyField(); }
, , , . - , ( , ), , - , ?
, . ( ).
, Super - ?
Super
Perhaps your superclass will provide an interface for interacting with this field in a general way, for example:
public abstract class Super<T> { protected T myField; public T getField() { return myField; } } public class Child extends Super<String> { public Child( String label ) { super.myField = label; } }
As indicated in this tuturial
A protected field or method is available for the class itself, its subclasses, and classes in one package.
This means that protected fields were designed to have these characteristics.
Only on a lighter note The only thing common in your hirarchy is one field then you should get rid of abstract class and Create one Marker Interface.
The only thing common in your hirarchy is one field then you should get rid of abstract class and Create one Marker Interface.