Home  |   STIU  |   WOW  |   SCJP  |   SCDJWS   |   JEE FAQ  |   About US  |  

FAQ
  Java FAQ
  JSP FAQ
  Servlet FAQ
 

Advertisement

XyzWs Java FAQ:
How to create instances of static nested classes and inner classes?


Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend


Previous Next vertical dots separating previous/next from contents/index/pdf Contents
Advertisement
XyzWs Java FAQ: How to create instances of static nested classes and inner classes?

How to create instances of static nested classes and inner classes?


The semantics for creating instances of static nested classes/inner classes can be confusing.

  • creating an instance of the inner class requires a reference to an instance of the enclosing class
  • creating an instance of the static nested class does not require an instance of the enclosing class

Here is an example which is a simple class that defines a static nested class and an inner class:

public class EnclosingClass {
    private String name = "instance name";
    private static String staticName = "static name";

    public static void main(String[] args) {
       EnclosingClass enclosingClass = new  EnclosingClass();
       EnclosingClass.InnerClass innerClass = enclosingClass.new InnerClass();
       EnclosingClass.StaticNestedClass staticNestedClass = new EnclosingClass.StaticNestedClass();
    }
    
    class InnerClass {
       InnerClass() {
          System.out.println(name);
          System.out.println(staticName);
       }
    }
    static class StaticNestedClass {
       StaticNestedClass() {
          System.out.println(staticName);
       }
    }
}

Nested classes can be confusing, but once you understand their purpose and get used to the semantics, there isn't a lot to them. If you'd like to learn more about the details of nested classes, check out the Nested Classes in XyzWS SCJP section.


Previous Next vertical dots separating previous/next from contents/index/pdf Contents

Support  | Feedback  | Help