Why is the need of Protected constructor in Abstract class in java

Sunny Gupta :

While reviewing the java code, I have seen that the constructor of an abstract class is made protected.

public abstract class A {
   protected A() {

   }
}

What

Abstract means to me is that you can't create the instance of this class and use this class after extending

.

And protected constructor also ensures that.

What is the point of doing two things, one making constructor protected and second making the class abstract for solving the same purpose.

ernest_k :

It's true that reducing the visibility of the constructor in an abstract class (from public to protected) changes nothing regarding the inability of code to directly instantiate the abstract class.

However, that is not the point. One makes the constructor protected just to control scopes, in the same way one makes member properties private.

Here's a modified version of the same class showing that the point is not to prevent instantiation:

public abstract class A {
    protected A() {
        this(0);
    }
    private A(int a) {
        // not accessible to anyone but members of A
        // the point is not to prevent instantiation, but to restrict access
    }
}

If making the constructor protected were meant to prevent instantiation, then one could argue that instantiation would be possible within the abstract class itself or its subclasses.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=144954&siteId=1