Static Nested Class In Java
Static nested class
When a static class is created inside another class, it is called as a static nested class in Java.
Static nested class can’t access the non-static data members and the methods. It can access the static data members of an outer class whether it is public, private or protected and it can be accessed through outer class name only.
Syntax
Class outer{
static class Nested_Ex{
}
}
Let’s see an example with the instance method, given below.
Code
- public class Animal {
- static int age = 10;
- static class Dog {
- void display() {
- System.out.println("Dog age is " + age);
- }
- }
- public static void main(String args[]) {
- Animal.Dog a = new Animal.Dog();
- a.display();
- }
- }
Output
In the example, mentioned above, we create the object of static nested class because it has an instance method display(). We don't need to create the object of Animal class because the nested class is static and static properties, methods or classes can be accessed directly. There is no need to create an object.
Let’s see an example, given below, with the static method.
Code
- public class Animal {
- static int age = 10;
- static class Dog {
- static void display() {
- System.out.println("Dog age is " + age);
- }
- }
- public static void main(String args[]) {
- Animal.Dog.display(); //no need to create the instance of static nested class
- }
- }
Output
In the example, mentioned above, the static member inside the static nested class due to which we don't need to create an instance of static nested class.
Summary
Thus, we learnt when a static class is created inside another class, it is called a static nested class in Java and also learnt how to create static nested class.