Java: Nested class

In Java, it is preferred that we create one main class and have classes nested in the main class.

This is a way to logically group classes together and it also increases encapsulation.

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. Static nested classes do not have access to other members of the enclosing class.

package JavaApp;

public class JavaApp {

    class FirstApp {

        void PrintOut() {

    public static void main(String[] args) {

        JavaApp x = new JavaApp();
        JavaApp.FirstApp y = FirstApp();

In the example above, FirstApp is nested within JavaApp class.  JavaApp class is like the main class of the file.

Notice how the method y is created in the program.  The first instance x of the main class JavaApp is first created.  y which is a second level instance is declared by using

JavaApp.FirstApp y = FirstApp();