简体   繁体   中英

Is there any way to define a private class in Java which only other classes in the same package can access it?

I've always had this question on top of my mind that why defining private classes within a package in Java is not possible like the way we can define it in a namespace in .Net .

Let's say I have a ds package in my Java Project. I have two classes in the names of Stack and Queue inside this package. Both of these classes need to make use of another class in the name of ListNode . ListNode is only required by other classes in the ds package, and it shouldn't be exposed to classes outside of the ds package.

I can define the ListNode as an inner classes. But in this case, I should define it in both Stack and Queue classes, and it's also redundant. Is there any design pattern to work around this? If not, please someone at least explain me why this is not possible in Java!

You can look into package private classes. docs

If you omit the public/private/protected from your class it is only accessible by other classes in the same package

The following table shows the access to members permitted by each modifier.

Access Levels
Modifier    Class   Package Subclass    World
public       Y        Y        Y          Y
protected    Y        Y        Y          N
no modifier  Y        Y        N          N
private      Y        N        N          N        

From here

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