Application Development Discussions
Join the discussions or start your own on all things application development, including tools and APIs, programming models, and keeping your skills sharp.
cancel
Showing results for 
Search instead for 
Did you mean: 

Why can't an abstract class have a protected constructor?

frankoverip
Explorer
0 Kudos
797

I created several classes that represent the different kinds of business partners we have in our system. All classes shall be instantiated only by a factory class, so they shall only have protected constructors.

I created an abstract class on top of the hierarchy that provides some common attributes. For these attributes I have created a constructor.

My problem is now that I cannot set the constructor of my abstract class to protected. I get an error message saying that the visibility of the constructor must not be more special than the visibility of the instance creation.

As the class is an abstract class there is no instance creation. So, did I miss something? Is this just a bug or are there any reasons for this?

Best regards

Frank

1 ACCEPTED SOLUTION

AndyBoolean
Participant
325

Hi frankoverip,
So the constructor method must always be under the public section in ABAP.

CLASS zcl_gilded_rose DEFINITION
PUBLIC
ABSTRACT
CREATE PUBLIC. PUBLIC SECTION. METHODS constructor. PROTECTED SECTION. PRIVATE SECTION. ENDCLASS.

You control who my instantiate the class via the CREATE PUBLIC ( PROTECTED / PRIVATE ) command.

Or do I not understand your question?

Regards
Andy

2 REPLIES 2

AndyBoolean
Participant
326

Hi frankoverip,
So the constructor method must always be under the public section in ABAP.

CLASS zcl_gilded_rose DEFINITION
PUBLIC
ABSTRACT
CREATE PUBLIC. PUBLIC SECTION. METHODS constructor. PROTECTED SECTION. PRIVATE SECTION. ENDCLASS.

You control who my instantiate the class via the CREATE PUBLIC ( PROTECTED / PRIVATE ) command.

Or do I not understand your question?

Regards
Andy

frankoverip
Explorer
0 Kudos
325

Hi Andy,

Thanks for your response. Although it did not really answer my question, it made me do some tests to prepare my answer. While doing so, it became clear to my why it is not problem that there is no protected constructor for abstract classes.

My error was that I expected a class inheriting a public constructor to become also public. But of course, this is not the case as I can still choose to allow only protected instantiation - which in a way makes the public constructor protected.

Thanks and regards

Frank