Java Program to demonstrate Inner class.
Objective
Write a Java program to demonstrate an Inner Class (Non-static Nested Class).
Algorithm / Approach
- Create an outer class
Personwith instance variables (name, id). - Inside it, create a non-static class
Address. - In the
display()method of Address, access both its own variables (hno, city) and the outer class's variables (name, id). - In main, instantiate the outer class first:
Person p = new Person();. - 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 thepobject 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)