Java Made Simple: Is it possible static class in Java?


Is it possible static class in Java?

The answer is both "YES" and "NO". Let us see.

Java comes with two types of classes – top-level classes and inner classes (also known as nested classes). A top-level class cannot be static where as a nested class can be static.

Top-level class cannot be static. See the compilation error on static class.
static class Demo
{
   // some code here
}

static class

It says access modifier static is not allowed here.

Static nested classes

A class declared in another class is known as nested class.

class OuterOne                        // top-level class or known as outer class
{
  class InnerOne	              // inner class or nested class
  {

  }
}

In the above code, OuterOne cannot be static and InnerOne can be declared static as follows.

class OuterOne                        // top-level class or known as outer class
{
  static class InnerOne	             // inner static class
  {

  }
}

That is, only nested classes can be declared static. But in general sense, it is not possible.

Nested classes are given a chance because to permit to call the nested classes without creating object of outer class.

Nested classes are discussed elaborately with example, explanation and screenshots at Static Nested Classes

Leave a Comment

Your email address will not be published. Required fields are marked *