The Java tutorials that I read, like to use nested classes to demonstrate a concept, a feature or use.
This led me to initially implement a sample project I created just like that: Lots of nested classes in the main activity class.
It works, but now I got a monstrous monolithic .java file. I find it somewhat inconvenient and I now intend to break to multiple .java files/classes.
It occurred to me, however, that sometimes there may be reasons not to take classes out of their enclosing class.
If so, what are good reasons to keep a module large, considering modularity and ease of maintenance?
Are there cases in which it is impractical (or even impossible) to convert a nested class to a toplevel class? In other words, is there a case in which only a nested class could satisfy certain functionality?
In Java programming, nested and inner classes often go hand in hand. A class that is defined within another class is called a nested class. An inner class, on the other hand, is a non-static type, a particular specimen of a nested class.
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.
Nested Class can be used whenever you want to create more than once instance of the class or whenever you want to make that type more available. Nested Class increases the encapsulations as well as it will lead to more readable and maintainable code.
Non-static nested classes are called inner classes. Nested classes that are declared static are called static nested classes. A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private.
It can be easier to read all the classes if they are in the same file. This is why this approach is good for example code.
However for real code, you should break your files/classes into manageable sizes. The longest class file in Java 6 is about 9000 lines long. I tend to keep classes shorter than this. ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With