Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the disadvantages of using a static nested class in Java? [closed]

Tags:

java

In the text I'm working through, the author shows a code example using a static nested class, and then comments that if the static nested class "bothers you", you can write it as a separate class.

Why would it bother you? What are the disadvantages of using a static nested class in Java?

like image 467
e.inglewood Avatar asked Nov 06 '12 19:11

e.inglewood


2 Answers

Advantage: What the author meant was a static nested class gets compiled into a totally separate .class than the outer class enclosing it. So, if it bothers you or over complicates the things or confuses you then better use it separately. A Static nested class doesn't depend on the outer class instance, it can run on it's own. Even a main function can be written inside the static nested class and invoked directly. And the benefit of it is you can have less number of objects created at runtime which wouldn't be the case with other types of nested classes.

Disadvantage The only disadvantage I can think of is a static nested class has access to both the protected and private members of the outer class. Say you have a class X and a class Y. In order for Y to access X's private members but not the rest of the world, making Y an Inner class of X helps. That satisfies the encapsulation thing by grouping them together.

But a Static Nested class doesn't care about accessibility modifiers of the Outer class while accessing it's members. Since it can live independently, it can allow somebody from outer world to mingle with the private members of the Outer class and hence break the encapsulation.

Treat the Static nested class as another top level class who can gain access to the private and protected members of the Outer class without using the Outer class's context/instance and freely sell them to external world for bad use.

For better understanding about Nested classes or anything in Java, I would recommend going through the Oracle docs before reading any book, http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html

like image 87
Arham Avatar answered Sep 22 '22 21:09

Arham


A nested class might bother a beginner because he doesn't understand it. The author was cautious not to confuse such a beginner, and to comfort him he offers a simple top-level class. On the other hand, a nested class is probably more appropriate in the example since it is quite possibly minimalistic in content and it helps readability to have all related things in one place.

like image 34
Marko Topolnik Avatar answered Sep 26 '22 21:09

Marko Topolnik