Java nested package visibility

2019-07-15 12:41发布

Often when i'm designing some new component of the project I'm haveing a limitation that i cant right way to work out...

Imagine a package "component" and in this component package you have some public classes/interfaces which are naturally designed to share publically and some classes/interfaces (ComponentSpecificStuff) that are needed in inner packages but those should not be visible from outside of package...

Now with current java possiblities only way I achieve this is by violating the (not expose Stuff outside "component" package) moment...

How do you workaround this?

标签: java package
1条回答
Juvenile、少年°
2楼-- · 2019-07-15 13:14

Yes you can do it till some extent by using internal keyword in package name.
Example you have a package

com.myPackage.component

you can have another package as

com.myPackage.component.internal.blahblah

When you use the keyword internal it is not exposed to other jars and not available for usage outside the jar but can be used inside the jar by another package. Here the internal package is extending com.myPackage.component further down the hierarchy. As quote by Jon Skeet Packages are not hierarchical as far as the compiler is concerned - the "hierarchy" is just human pattern matching for organization, effectively. That is what I mean by extending the package further.


EDIT

You can define a class package private by not giving any access modifier to the class Example :

class PackagePrivateClass{

}

You can import this class in the same package but outside the package it doesn't allow you to use it.

查看更多
登录 后发表回答