Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-public top-level class vs static nested class

It seems to me that non-public top-level classes and static nested classes essentially perform the same tasks when creating a helper class.


A.java


public class A 
{
    public static main (String[] args)
    {
        AHelper helper = new AHelper();     
    }
}
class AHelper {}

A.java


public class A
{
    public static main (String[] args)
    {
        A.AHelper helper = new A.AHelper();     
    }

   static class AHelper {}
}
 

Aside from how they are referenced, there seems to me very little difference between the two ways of creating a helper class. It probably comes down mostly to preference; does anyone see anything I'm missing? I suppose some people would argue that it's better to have one class per source file, but from my perspective it seems cleaner and more organized to have a non-public top-level class in the same source file.

like image 703
Stephen Avatar asked Jan 27 '10 16:01

Stephen


People also ask

Why can we have a static inner class but not a static top level class in Java?

Because the static keyword is meant for providing memory and executing logic without creating Objects, a class does not have a value logic directly, so the static keyword is not allowed for outer class and mainly as mentioned above static can't be used at Package level.

What is the difference between static and non-static class?

A static class is similar to a class that is both abstract and sealed. The difference between a static class and a non-static class is that a static class cannot be instantiated or inherited and that all of the members of the class are static in nature.

What is a non-static nested class also known as?

A non-static nested class is a class within another class. It has access to members of the enclosing class (outer class). It is commonly known as inner class . Since the inner class exists within the outer class, you must instantiate the outer class first, in order to instantiate the inner class.


1 Answers

In neither example do you have one class per source file. But generally, you use a static nested class to signify that it is only intended to be used within its enclosing class (forcing it to be referenced as A.AHelper). That is not so clear if you move that class to the top level.

From the Sun tutorial:

Logical grouping of classes—If a class is useful to only one other class, then it is logical to embed it in that class and keep the two together. Nesting such "helper classes" makes their package more streamlined.

like image 116
danben Avatar answered Sep 19 '22 22:09

danben