简体   繁体   中英

Does nested class (inner or static) that is private may has method with public acesses?

I'm reading a book for java beginners. i saw an example that private nested inner class was declared with a public method. Can someone explain me the meaning and how can i decide if a private nested class (static/inner) methods should be private or public?

A private nested class is only visible inside its enclosing class, and the enclosing class (and other nested classes) can access its private methods.

So making their methods public or private doesn't matter much to the compiler, unless of course the nested class extends a base class or implements an interface, and thus has to have its overriding methods public. Making methods public can also be necessary of they're called using reflaction (for example if its onstances are serialized as JSON or XML, or if they're accessed in a JSP).

I tend to choose what to make public and private using the same rules as if the class wasn't nested. That makes it clearer (to me) that some private methods are not not part of its public API and thus not supposed to be used outside the nested class itself. And if I ever refactor the nested class as a top-level class, I don't need to change anything.

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