Package Protected Constructor

Package Protected Constructor

I need to extend class A which resides in a different package, butclass A has only one constructor which is package protected. I get a compile error in class B, which extends class A, saying that theclass A constructor is not visible from class B. I know this iscorrect, but how do I extend and initialize class A and access itspackage protected fields?

If you have written the source code to class A, then you are incomplete control and can resolve the problem. If class A was intendedto be subclassed outside of its package, then you have run into adesign problem. Any class that is intended to be extended by classesoutside of its package should declare most of its members eitherpublic or protected. Members which are to be publicly accessible, butnot polymorphic should be declared final. Members which comprise theexternal interface exported by the class should be public. Memberswhich are not part of the external class interface, but which areneeded by subclasses should be declared protected. Only if you wantto limit subclassing or use to a particular package should a constructor orother members be declared package local. Additionally, in some cases,you may want classes in a package to liberally access each other’spackage local member variables for performance reasons. Finally,member functions and variables which are only to be accessed by theclass should be declared private.

It is a common practice in C++ and Java to declare a constructorprotected if you only want subclasses to be able to use the class. InJava, you may declare a class constructor package local in order tolimit its use to a particular package. If you are finding you need tosubclass such a class outside of its package, you should redeclare itsconstructor protected. If you need to instantiate such a classoutside of its package, you should redeclare its constructor public.It also may be that your class B should be placedin the same package as class A if the original design decision tolimit access to class A to within the package was sound.


About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist