Java Program to demonstrate static Nested class.
Objective
Write a Java program to demonstrate a Static Nested Class.
Algorithm / Approach
- Create an outer class
Personwith static fields (name, id). - Inside
Person, create astatic class DOB(Date of Birth). - Add a
display()method insideDOBto print the outer class's static fields alongside the DOB fields. - In main, set the static fields of
Person. - Instantiate the static nested class using:
Person.DOB p = new Person.DOB();.
Person.java
class Person {
static String name;
static int id;
static class DOB {
int d,m,y;
void display() {
System.out.println("Name- "+name);
System.out.println("Id- "+id);
System.out.println("DOB- "+d+":"+m+":"+y);
}
}
}
class Main {
public static void main(String[] a)
{
Person.name = "Alok";
Person.id= 12;
Person.DOB p = new Person.DOB();
p.d = 4;
p.m = 3;
p.y = 1992;
p.display();
}
}
Expected Output
Name- Alok Id- 12 DOB- 4:3:1992
Explanation of the Program
- A static nested class is essentially a normal class that has just been nested inside another class for packaging/organizational convenience.
- Because it is static, it does NOT require an instance of the outer class to be created. You can instantiate it directly using the outer class name (
new Person.DOB()). - However, this also means it can ONLY access the static members of the outer class. It cannot access normal (instance) variables of the outer class.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)