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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With