Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

protected vs public constructor for abstract class? Is there a difference?

This question is out of curiosity. Is there a difference between:

public abstract class MyClass {     public MyClass()     {     } } 

and

public abstract class MyClass {     protected MyClass()     {     } } 

Thanks.

like image 794
Marlon Avatar asked Dec 26 '10 00:12

Marlon


People also ask

Should abstract classes have protected constructors?

An abstract class by definition cannot be instantiated directly. It can only be instantiated by an instance of a derived type. Therefore the only types that should have access to a constructor are its derived types and hence protected makes much more sense than public.

Can abstract class have protected members?

Yes, you can declare an abstract method protected. If you do so you can access it from the classes in the same package or from its subclasses.

Can an abstract class have a private constructor?

Answer: Yes. Constructors in Java can be private. All classes including abstract classes can have private constructors. Using private constructors we can prevent the class from being instantiated or we can limit the number of objects of that class.

When would you use a protected constructor?

A protected constructor means that only derived members can construct instances of the class (and derived instances) using that constructor. This sounds a bit chicken-and-egg, but is sometimes useful when implementing class factories. Technically, this applies only if ALL ctors are protected.


1 Answers

They are the same for all practical purposes.

But since you asked for differences, one difference I can think of is if you are searching for the class's constructor using reflection, then the BindingFlags that match will be different.

BindingFlags flags = BindingFlags.Public | BindingFlags.Instance; var constructor = typeof(MyClass).GetConstructor(flags, null, new Type[0], null); 

This will find the constructor in one case, but not the other.

like image 103
Mark Byers Avatar answered Sep 19 '22 11:09

Mark Byers