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.
Most Recent java Faqs
- How to uncompress a file in the gzip format?
- How to make a gzip file in Java?
- How to use Java String.split method to split a string by dot?
- How to validate URL in Java?
- How to schedule a job in Java?
- How to return the content in the correct encoding from a servlet?
- What is the difference between JDK and JRE?
Most Viewed java Faqs
- How to read input from console (keyboard) in Java?
- What are class variables in Java?
- How to Retrieve Multiple Result Sets from a Stored Procedure in JDBC?
- What are local variables in Java?
- How to Use Updatable ResultSet in JDBC?
- How to Use JDBC Java to Create Table?
- Why final variable in Enhanced for Loop does not act final?