Java inner classes explained with examples: Static nested classes vs Non-static inner classes
Introduction to inner classes in java
In java, a class can be declared inside another class. Such classes known as nested classes.
In java, a class can be declared inside another class. Such classes known as nested classes.
Nested classes help organize related classes, improve encapsulation and make code easier to maintain.
Java supports four types of nested classes:
Java supports four types of nested classes:
- Static nested classes
- non-static member inner classes
- Local inner classes
- Anonymous inner classes
In this tutorial, we will focus on the two commonly discussed types: static nested classes and non-static inner classes.
1. What is a static nested class in java?
A static nested class is a class declared inside another class using the static keyword.
Unlike a non-static inner class , a static nested class doesn't require an instance of the outer class to be created.
For example:
public class OuterClass{
private static String message = "Hello Java";
static class InnerClass{
public void display(){
System.out.println(message);
}
}
}
We can create an object of the static nested class without creating an object of the outer class.public class OuterInnerDemo{
public static void main(String[] args){
OuterClass.InnerClass nestedObject =
new OuterClass.InnerClass();
nestedObject.display();
}
}
Output:
Hello Java
Notice that we used OuterClass.InnerClass to create the object.
Note: We can not declare an outer class static. We can only use static keyword
with inner classes.
2. What is a non-static inner class in java?
Benefit of static inner
classes:
static inner class doesn’t
contain a reference of outer class. So, on screen rotation [In Mobile device, like Android], it doesn’t create m/m
leak. While non-static inner class contains reference of
outer class and can cause m/m leak.2. What is a non-static inner class in java?
Unlike a static nested class, a non-static inner class is associated with an instance of its outer class.
Therefore, we must first create an object of the outer class before creating an object of the inner class.
For example:
public class OuterClass {
private String message = "Hello Java";
class InnerClass {
public void display() {
System.out.println(message);
}
}
}
To create an object of the non-static inner class:
public class OuterInnerDemo {
public static void main(String[] args) {
OuterClass outer = new OuterClass():
OuterClass.InnerClass innerObject =
outer.new InnerClass();
innerObject.display();
}
}
Output:
Hello Java
Notice the syntax:
outer.new InnerClass();
We need an existing instance of the outer class to create its non-static inner class object.
Please leave a comment, if this post is really helpful.
Thanks