Is there any point in an abstract class with an open constructor instead of a protected one?

Since an abstract class cannot be created, and since protected members are always visible to subclasses, it does not seem to matter if its constructors are public or protected.

Is there any example where a public constructor might matter compared to a protected one? I usually prefer the most restrictive level of access that is applicable.

+6
source share
2 answers

No, there is no good reason to create a public constructor for an abstract class: you cannot create an instance of your abstract class without first subclassing it, and the language deals with the corresponding corner cases for you.

In particular, if you want to anonymously subclass your abstract class, which means that you cannot provide your own constructor in a subclass, the language will provide you with one of them based on the signature of the protected constructor of your abstract base class

abstract class Foo { protected int x; protected Foo(int x) {this.x = x;} public abstract void bar(); } public static void main (String[] args) { Foo foo = new Foo(123) { // <<== This works because of "compiler magic" public void bar() {System.out.println("hi "+x);} }; foo.bar(); } 

In the above example, it looks like the protected constructor of an abstract class is called, but it isn’t: the compiler builds a visible constructor for your anonymous class * that calls when you write new Foo(123) .

Demo version

* Actual visibility by default. Thanks, Pshemo, for discovering the error and delivering a good test case .

+8
source

It makes no sense to create a constructor for the abstract class public. But you can be sure that no one will instantiate directly.

0
source

Source: https://habr.com/ru/post/977297/


All Articles