Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modularity in Java: top level vs. nested classes

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?

like image 755
an00b Avatar asked Mar 18 '11 16:03

an00b


People also ask

Is there any difference between nested classes and inner classes in Java?

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.

What are the advantages disadvantages of nested classes?

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.

Is it good practice to use nested classes?

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.

What is the difference between nested and inner classes?

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.


1 Answers

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. ;)

like image 138
Peter Lawrey Avatar answered Nov 07 '22 01:11

Peter Lawrey