Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to demonstrate Method Local Inner class.

Java Code Example — Inner Class Programs

ADVERTISEMENT

Java Program to demonstrate Method Local Inner class.

Objective

Write a Java program to demonstrate a Method-Local Inner Class.

Algorithm / Approach

  1. Create an outer class Person with a method display().
  2. Inside the actual display() method body, declare a completely new class Address.
  3. Inside the same method (below the class definition), instantiate the Address class and call its methods.
  4. In main, just create a Person and call display().
Person.java
class Person {
 String name = "Alok";
 int age = 22;
 public void display() {
  System.out.println("Name: "+name);
  System.out.println("Age: "+age);
  class Address {
   int hno =102;
   String city ="Trinagar";
   int pin=110035;
   void show() {
   System.out.print("Address: ");
   System.out.println(hno+"/"
       +city+"-"+pin);
   }
  }
  Address a = new Address();
  a.show();
 }
}
class Main{
 public static void main(String[] a)
 {
  Person p =new Person();
  p.display();
 }
}

Expected Output

Name: Alok
Age: 22
Address: 102/Trinagar-110035

Explanation of the Program

  • Classes can be defined almost anywhere in Java, even directly inside a method block!
  • A Method-Local Inner Class behaves like a local variable: it is completely invisible to the outside world. Not even other methods inside the same Person class know that the Address class exists.
  • This is the ultimate form of encapsulation. It is used when you need a complex helper object strictly for the duration of one single method execution.

Complexity

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