简体   繁体   中英

Why can't sub-packages see package private classes?

Okay so, I have this project structure:

package AB

  • class SuperClass (this class is marked package private)

package ABC

  • class SubClass (inherits from super class)

I'd rather not make SuperClass publicly visible... It is really just a utility class for this specific project (AB).

It seems to me that SubClass should be able to see SuperClass , because package ABC is a subpackage of AB.. but this is not the case.

What would be the best way to resolve this issue? I don't think it makes sense to move everything in ABC up to AB or move AB down to ABC.. mainly because there will probably be an ABD which inherits from stuff in AB as well...

I'm a bit new to Java, so be nice :D (I'm a C++ and .NET guy)

Packages are unique identifiers. You cannot make them follow the inheritance rules. Package and SubPackages are not analogical to Super and Sub classes.

I dont see any flaws in making the class that you wanted to use in the sub package to be visible to the outside world. I would be interested to know how this criterion is handled in C++/.net (as I am a java guy :) )

Your best bet is to declare the (default) constructor(s) of SuperClass as protected . This way only classes in the same package and subclasses regardless of the package can instantiate it and extend from it.

Why not put them in the same package level?

Could you somehow use composition instead of inheritance? I've been trying to do more of this myself after reading Effective Java. Not sure if this is possible given your needs, but it might be worth considering.

Good luck.

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