Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to demonstrate Inner class.

Java Code Example — Inner Class Programs

ADVERTISEMENT

Java Program to demonstrate Inner class.

Objective

Write a Java program to demonstrate an Inner Class (Non-static Nested Class).

Algorithm / Approach

  1. Create an outer class Person with instance variables (name, id).
  2. Inside it, create a non-static class Address.
  3. In the display() method of Address, access both its own variables (hno, city) and the outer class's variables (name, id).
  4. In main, instantiate the outer class first: Person p = new Person();.
  5. Use the outer object to instantiate the inner class: Person.Address add = p.new Address();.
Person.java
class Person {
 String name;
 int id;
class Address {
  int hno;
  String city;
  int pin;
  void display() {
   System.out.println("Name: "+name);
   System.out.println("Id: "+id);
   System.out.println("Address: "+hno+"/"
              +city+"-"+pin);
  }
 }
}
class Main {
 public static void main(String[] a) {
  Person p = new Person();
  Person.Address add =p.new Address();
  p.name= "Alok";
  p.id = 12;
  add.hno = 102;
  add.city = "Trinagar";
  add.pin = 110035;
  add.display();
 }
}

Expected Output

Name: Alok
Id: 12
Address: 102/Trinagar-110035

Explanation of the Program

  • Unlike a static nested class, a standard Inner Class is intimately tied to a specific instance of the outer class.
  • You cannot create an Address without first creating a Person to attach it to. This is why the instantiation syntax (p.new Address()) requires the p object reference.
  • The benefit is that the inner class has full access to ALL members (even private ones) of the specific outer class instance it belongs to.

Complexity

Time Complexity O(1)
Space Complexity O(1)
ADVERTISEMENT