Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a top level class in java?

Tags:

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.

like image 740
Harsha Jayamanna Avatar asked Jan 18 '17 08:01

Harsha Jayamanna


People also ask

Which is the top most class in Java?

The Object class is the parent class of all the classes in java by default. In other words, it is the topmost class of java.

Can a top level class be private or protected in Java?

No, we cannot declare a top-level class as private or protected. It can be either public or default (no modifier). If it does not have a modifier, it is supposed to have a default access.

Which access modifiers is a top level class?

Access level modifiers determine whether other classes can use a particular field or invoke a particular method. There are two levels of access control: At the top level— public , or package-private (no explicit modifier). At the member level— public , private , protected , or package-private (no explicit modifier).

Can we make a top level class as static in Java?

We can't declare outer (top level) class as static 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.


2 Answers

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.

like image 60
yshavit Avatar answered Oct 04 '22 02:10

yshavit


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.

like image 34
Erivan Avatar answered Oct 04 '22 02:10

Erivan