Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to demonstrate static Nested class.

Java Code Example — Inner Class Programs

ADVERTISEMENT

Java Program to demonstrate static Nested class.

Objective

Write a Java program to demonstrate a Static Nested Class.

Algorithm / Approach

  1. Create an outer class Person with static fields (name, id).
  2. Inside Person, create a static class DOB (Date of Birth).
  3. Add a display() method inside DOB to print the outer class's static fields alongside the DOB fields.
  4. In main, set the static fields of Person.
  5. 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)
ADVERTISEMENT