Java Program to demonstrate Method Local Inner class.
Objective
Write a Java program to demonstrate a Method-Local Inner Class.
Algorithm / Approach
- Create an outer class
Personwith a methoddisplay(). - Inside the actual
display()method body, declare a completely new classAddress. - Inside the same method (below the class definition), instantiate the Address class and call its methods.
- 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
Personclass know that theAddressclass 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)