Last active
February 7, 2020 07:39
-
-
Save iamminster/d7a8a8f5fb58842ee77cfb4aa492de99 to your computer and use it in GitHub Desktop.
Clarify on nested class in Java (Refer: https://stackoverflow.com/questions/70324/java-inner-class-and-static-nested-class)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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