Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
246 views
Welcome To Ask or Share your Answers For Others

1 Answer

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. E.g.:

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...