Richard Walton
Richard Walton

Reputation: 4785

Abstract class constructor access modifier

An abstract class can only be used as a base class which is extended by some other class, right? The constructor(s) of an abstract class can have the usual access modifiers (public, protected, and private (for internal use)). Which of protected and public is the correct access modifier to use, since the abstract type seems to indicate that technically a public constructor will act very much protected? Should I just use protected on all my constructors?

Upvotes: 29

Views: 15271

Answers (4)

Jordan Stewart
Jordan Stewart

Reputation: 674

An abstract class's constructor can only be called from the implementation's constructor, so there is no difference between it being public or protected. E.g.:

public class Scratch
{
    public static abstract class A
    {
        public A( int i ) {}
    }
    
    public static class B extends A
    {
        private B() { super(0); };
    }
}

Upvotes: 24

JaredPar
JaredPar

Reputation: 754655

At the very least, an abstract class should have a protected constructor. It's not strictly necessary since it's not possible to use the constructor anyway but it makes the contract explicit.

Another option is to make the constructor private. This is only a good idea though if all of the implementations of the class are private inner classes. A rare but useful example.

Upvotes: 1

Nrj
Nrj

Reputation: 6831

since the abstract type seems to indicate that technically a public constructor will act very much protected

Umm... for abstract classes this constructor scope [public or protected] is not of much difference since the instantiation is not allowed [even if public]. Since it is meant to be invoked by the subclass, it can invoke either public or protected constructor seamlessly.

Its completely on choice what to use. I generally prefer public as it is in most of the cases.

Upvotes: 1

IAmCodeMonkey
IAmCodeMonkey

Reputation: 1568

If this behavior is true, and I'm not sure it is, you should always use the most restricted scope available for your application to function. So in that case, I would recommend using protected.

Upvotes: 7

Related Questions