Reputation: 1107
I have a silly doubt, but I would like to hear some opinions about it.
I have a super class (MySuperClass), and then, I have like 70 classes inheriting from this super class (Bean classes).
The purpose of this super class is to implement the "toString" method using reflection, and this way, I'm making sure that all of this 70 classes will have the toString method. These 70 classes are beans, and the final purpose is to log the class information instead of just the instance of the class.
However, that is not what I want to discuss, what I would like to hear from you is what do you think about having a protected constructor for the superclass, benefits and disadvantages of having this, and not only for this particular case but for other situations or scenarios that you can imagine.
Regards,
Fer
Upvotes: 3
Views: 3017
Reputation: 86506
A protected constructor has one useful trait that isn't available with abstract classes: classes in the same package, subclasses, and static methods within the class itself can create instances of the class, while outsiders can't. Abstract classes can't be instantiated at all, regardless of the constructor's accessibility.
With that said, i would prefer to have the class be abstract. Protected constructors can't prevent a subclass, or any class in the same package, from saying BaseClass x = new BaseClass();
. A protected constructor says to me "The code may be instantiating this class somewhere", and gives me yet another thing to have to keep track of.
Upvotes: 1
Reputation: 2927
if u want to create only one instance using a static method that return an instance of this type you can make the constructor protected. benefits memory allocation when the object is to heavy and creating many instances will affect the memory
public class A{
private static A instance = null;
protected A() {
// Exists only to defeat instantiation.
}
public static A getInstance() {
if(instance == null) {
instance = new A();
}
return instance;
}
}
Upvotes: 1
Reputation: 183251
If your goal is to ensure that MySuperClass
is never instantiated directly via new MySuperClass()
, only its subclasses are, then it makes more sense to declare the class abstract
; see http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html. That's really the whole point of abstract classes. The constructor can then be either public
or protected
, it doesn't really matter.
The reason to have all constructors protected
in a non-abstract
class would be if you do intend to instantiate the class itself, using new MySuperClass()
, but only want it to be instantiated by subclasses and other members of its package (such as a "factory" object). That doesn't sound like what you're trying to do, though.
Upvotes: 6