'What is a top level class in java?

  • What is a top level class in java?
  • What is the definition of a top level class in java ?

I know that this is a basic question, but i could not find a clear and simple answer for this question.



Solution 1:[1]

It's simply any class that's not a nested class. If your file is Foo.java, and your class is Foo, then it's a top level class.

// in Foo.java:

public class Foo { // top level class

    public static class NestedBar { // nested class
    }

}

I had always thought this was an informal term, but it turns out it's actually defined in the JLS:

A top level class is a class that is not a nested class.

A nested class is any class whose declaration occurs within the body of another class or interface.

Solution 2:[2]

The definition posted is correct, maybe another definition could be: a top-level class is the defined class with the same name of the file '.java' where it's in. however, just as an observation, for the case showed, a nested (not a top-level) 'static' class has the same behavior of a top-level class, in terms of the interaction with the instance members of the class where it has been nested.

Solution 3:[3]

A .java file can contain more than one class. At most, one of them can have a public access modifier, and the others must be default access modifier. They can be also final or abstract but not both at once. So, each non-nested independent class defined in a .java file is a top-level class.

For example, each class is a top-level class in following example.

public class Animal {  
    private String name; 
} 
class Animal2 {}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Andy Turner
Solution 2
Solution 3 snr