Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a superclass protected field which is only used in a subclass bad practice?

Tags:

java

I have a superclass like this which I expect alot of 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 these classes will need to use an instance of myField. However the superclass does not. Have I made a bad design decision somewhere?

like image 709
mogronalol Avatar asked Sep 06 '12 14:09

mogronalol


People also ask

Are protected fields bad?

Public and/or protected fields are bad because they can be manipulated from outside the declaring class without validation; thus they can be said to break the encapsulation principle of object oriented programming.

Can a superclass be a subclass?

The class from which the subclass is derived is called a superclass (also a base class or a parent class). Excepting Object , which has no superclass, every class has one and only one direct superclass (single inheritance).

Can protected method be accessed by subclass?

Yes, the protected method of a superclass can be overridden by a subclass.

Can subclass access protected fields superclass Java?

The protected modifier allows a subclass to access the superclass members directly. But the access should be made inside the subclass or from the same package.


2 Answers

Not necessarily. If all the subclasses need the same field for the same reason, then that's no different than providing any other common functionality in a base class. as your classes grow you may find that you add common functionality which uses this field (e.g. referencing it in an equals/hashCode method).

Now, if the field is of type Object and each sub-class shoves something completely different into it, i would consider that a code smell.

like image 136
jtahlborn Avatar answered Oct 22 '22 02:10

jtahlborn


Well IMHO, a field should not be present in a class if it's not really used by that class. What it seems to me that you really want here is to have a base class that tells its subclasses "you should ALL have some way of keeping state for X but I (the base class) will not modify that X state, in which case you should make an abstract method in order to convey that message, something like this:

public abstract class Super {
    protected abstract Object getMyField();
}
like image 5
Shivan Dragon Avatar answered Oct 22 '22 03:10

Shivan Dragon