Sunny Gupta
Sunny Gupta

Reputation: 7067

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

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.

Upvotes: 5

Views: 4945

Answers (2)

Eran
Eran

Reputation: 393781

Making the constructor protected doesn't prevent other classes from the same package or other classes that extend this class from instantiating the class using this constructor. Therefore the abstract keyword is required to prevent instantiating.

You can declare the constructor of an abstract class as public, but you still won't be able to instantiate this class, so it's pointless. On the other hand, a private constructor will not be usable by sub-classes of your abstract class (only be other constructors of the abstract class itself). Hence, any constructor of the abstract class that should be available to all sub-classes of the abstract class should be protected.

Of course, in your particular example there's no need to declare the constructor at all, since it has an empty body and there are no other constructors. This means the compiler will generate a parameter-less constructor with an empty body anyway.

Upvotes: 5

ernest_k
ernest_k

Reputation: 45309

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.

Upvotes: 4

Related Questions