Skip to content

Instantly share code, notes, and snippets.

@iamminster
Last active February 7, 2020 07:39
Show Gist options
  • Save iamminster/d7a8a8f5fb58842ee77cfb4aa492de99 to your computer and use it in GitHub Desktop.
Save iamminster/d7a8a8f5fb58842ee77cfb4aa492de99 to your computer and use it in GitHub Desktop.
// There are 2 types of nested class in Java: 1. Static nested class 2. Non-static nested class, which is called inner class
// So, Inner class is non-static nested class.
// Example:
public OuterClass {
public InnerClass {}
}
// An instance of InnerClass can only exists within an instance of OuterClass
// and has direct access (through reference) to the methods and fields of instance of OuterClass.
// To initiate an InnerClass, we need to initiate OuterClass first.
// Then create the instance of InnerClass within the outer instance using this syntax:
OuterClass outerObj = new OuterClass();
OuterClass.InnerClass innerObj = ourterObj.new InnerClass();
// Java does not have a top-level static class.
// However, it does have "nested static class".
// Example:
public OuterClass {
public static InnerClass {
private innerState;
private void innerMethod();
public static void staticInnerMethod();
}
}
// A static nested class is a normal class, but does not implicitly have a reference to the instance of outer class.
// So it can only access the static members of outer (enclosing) class.
// Static nested class can have instance and static methods.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment