by Dinesh Thakur Category: Inheritance

A static nested class or a top-level class is a class that is declared inside another class with a static modifier. Like static methods, a static nested class can only refer directly to static members of the enclosing classes, even if those members are private.

The following example demonstrates the use of static nested class.

class outer

      private double i = 11.7 ;
      private static String str = "Hi Programmers";
      static class inner
        int j ;
        public void display()
           j = 51;
          System.out.println("j = " + j);
          //System.out.prinln("i = "  +  i);   illegal statement
          System.out.println("str = " +  str);
class StaticClass
       public static void main(String[] args)
          outer.inner innobj =new outer.inner(); //create instance of                                       
                                            //static nested class

Static Nested Classes Java Example

As static keyword is used in the innerclass so it is a static class. The str variable is declared static so it can be accessed in the static class. The variable i is not declared static so it cannot be accessed in the class

About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.

Search Content

Popular Article