简体   繁体   中英

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?

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

This is not correct. An abstract class cannot be directly instatiated by calling its constructor, however, any concrete implementation will inherit the abstract class' methods and visibility

So the abstract class can certainly have public constructors.

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

public class Scratch
{
    public static abstract class A
    {
        public A( int i ) {}
    }

    public static class B extends A
    {
        private B() { super(0); };
    }
}

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM