The semantics for creating instances of static nested classes/inner classes can be confusing.
Click below links to know more
- 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.
Click below links to know more
Comments
Post a Comment