Scientech Easy Method Local Inner Class in Java | Example Programs | Scientech Easy

Saturday, March 9, 2019

Method Local Inner Class in Java | Example Programs

Method Local Inner Class in Java


An inner class which is declared inside a method of the outer class is called method local inner class. Its scope is limited to the block of a method in which it is declared. Therefore, its declaration cannot use any access modifiers such as public, protected, private, and non-access modifier such as static. Method local inner class can also be declared inside the constructor, static initializers, and non-static initializers. The only applicable modifiers for method local inner class is final, abstract, and strictfp. 
The figure shows an example of a method local inner class. 
Method local inner class in Java.

How to instantiate Method local inner class in Java


Since an inner class is defined inside the method of an outer class. Therefore, to create an instance of a local inner class in Java, an instance or object of the local inner class is also declared in the same method in which a local inner class is declared. An inner class is called when that method is called. A local inner class cannot be instantiated from outside the block of the method where it is created. 

You can access a method local inner class only within the method where you declare. Outside of the method, you cannot access because it is local to that method. Therefore, a method local inner classes are the most rarely used in all types of the inner class because of its less scope.
Let's see a simple example program to understand the concept of instantiating a method local inner class.
Program source code 1:
    package innerClass; public class OuterClass { // An instance method of class OuterClass. public void display(){ // Declaration of a method local inner class. class InnerClass { public void msg(){ System.out.println("I am in Local inner class"); } } // Here, create an instance of a method local inner class and call the msg() method using object reference variable ic. InnerClass ic=new InnerClass(); ic.msg(); } public static void main(String[] args) { // Create an object of the outer class OuterClass. OuterClass oc=new OuterClass(); oc.display(); } }
    Output: I am in Local inner class

What is the need/purpose of a method local inner class in Java?


The purpose or need of a method local inner class in Java is to define a specific method whose functionality is required repeatedly. Method-Local inner classes are the best suitable to meet nested method requirements. Let's understand this concept by taking a suitable example.
Suppose we declare a class Test. Inside the class, we have declared a method m1(). Now inside the method m1(), we have declared a method sum() with two parameters x and y whose data types are int. Assume that we have to calculate the sum of two numbers with different four sets of two values. 

See the below code. Is this code, right?
Program source code 2:
    package innerClass; public class Test1 { public void m1(){ void sum(int x, int y){ System.out.println("Sum of two numbers: " +(x+y)); } } public static void main(String[] args){ Test1 t=new Test1(); t.m1(); t.sum(20,30); t.sum(10,40); t.sum(50,50); t.sum(100,100); } }
Maybe your answer will be yes that we can declare a method inside the m1() and can call that method based on our requirements because the best reusable component is a method only. But the code is wrong. why?
This because declares a method inside another method is not possible in Java. Java does not allow the nested method concept. In this case, how will you fix this code?

There are two ways to fix this code. 
First way: Declare this method at the class level and call the sum method with different values but if we assume that this sum functionality is required only for the m1(). Outside the m1(), it is not required. So, we cannot declare at the class level. In this case, we will go for the second way.

Second way: Inside a method, we cannot declare a method but we can declare a local inner class within a method. Inside the inner class, we will place sum() and call with different sets of values. Let's see the code.
Program source code 3:
    package innerClass; public class Test1 { public void m1(){ // Method-local inner class starts here. class InnerClass { public void sum(int x, int y){ System.out.println("Sum of two numbers: " +(x+y)); } } InnerClass ic=new InnerClass(); ic.sum(10, 20); ic.sum(20, 30); ic.sum(30, 40); ic.sum(40, 50); } public static void main(String[] args){ Test1 t=new Test1(); t.m1(); } }
    Output: Sum of two numbers: 30 Sum of two numbers: 50 Sum of two numbers: 70 Sum of two numbers: 90
Thus, we can solve the problem of repeated functionality inside a particular method. 

Accessing the instance variables of outer class as well as local variables of method local inner class in Java


Since the object of an inner class exists within an object of its outer class. Therefore, a local inner class can access the instance variables of its outer class as well as local variables which are in scope. This is because the instance variables of the outer class exist throughout the life cycle of the object of the method local inner class. Let's take an example program to see the concept.
Program source code 4:
    package innerClass; public class AccessingVar { // Instance variables of outer class. int a=20; static int b=30; // Static variables of outer class. // Instance method of the outer class. public void m1(){ // Instance area. class InnerClass { // Local variables of inner class. int c=30; public void printSum(){ System.out.println("Sum of three numbers: " +(a+b+c)); // Accessing instance, static, and local variables inside the method local inner class. } } InnerClass ic=new InnerClass(); ic.printSum(); } public static void main(String[] args) { // Create an object of the outer class. AccessingVar av=new AccessingVar(); av.m1(); } }
    Output: Sum of three numbers: 80

Declaration of method local inner class inside the instance & static method


We can declare a method local inner class in both instance method and static method but there is a small difference between them. let's see an example program to understand the difference between them.
Program source code 5:
    package innerClass; public class OuterClass1 { int x=10; // Instance variable of class OuterClass1. static int y=20; // Static variable of class OuterClass1. // Declaration of the static method. static void m3(){ System.out.println("I am in OuterClass1 static method"); } // Declaration of an instance method. public void m1(){ // Instance area of m1(). // Method local inner class starts here. class InnerClass1 { public void m2() { System.out.println("Value of x: " +x); System.out.println("Value of y: " +y); m3(); } } // Here create an object of class InnerClass1 InnerClass1 ic=new InnerClass1(); ic.m2(); } public static void main(String[] args) { OuterClass1 oc=new OuterClass1(); oc.m1(); } }
    Output: Value of x: 10 Value of y: 20 I am in OuterClass1 static method
Key points:
If you declare inner class directly inside an instance method, you can directly access both static and non-static members from that method local inner class.
Program source code 6:
    package innerClass; public class OuterClass2 { int x=10; // Instance variable of class OuterClass1. static int y=20; // Static variable of class OuterClass1. // Declaration of the static method. static void m3(){ System.out.println("I am in OuterClass1 static method"); } // Declaration of a static method in OuterClass2. public static void m1() { // This is a static area of m1(). So we can call only static members. // Method local inner class starts here. class InnerClass1 { public void m2() { // System.out.println("Value of x: " +x); // Say line (1). System.out.println("Value of y: " +y); m3(); } } // Here create an object of class InnerClass1 InnerClass1 ic=new InnerClass1(); ic.m2(); } public static void main(String[] args) { OuterClass2.m1(); } }
    Output: Value of y: 20 I am in OuterClass1 static method
Since m1() method is declared as static. Therefore, at line 1, we will get compile time error: cannot make a static reference to the non-static field x.

Key points:
If you declare a method local inner class inside a static method of the outer class, you can access only static members of the outer class directly from the method local inner class. You cannot access instance members from the static area. So, this is the difference between the declaration of a method local inner class inside the instance and static method.

Can we access the local variables of a method in which a method local inner class is declared in Java?


A method local inner class cannot access the local variables of method in which it is declared because the local variables in a method exist only during the execution of that method. i.e the local variables will be created while executing the method. Once the method execution is over, all the local variables become destroyed and inaccessible. Let's see a simple example program and its output.
Program source code 7:
    package innerClass; public class AccessingLocalVar { public void m1(){ int x=20; // local variable of m1(). class InnerClass { public void printSum(){ System.out.println(x); // Compile time error. } } InnerClass ic=new InnerClass(); ic.printSum(); } public static void main(String[] args) { // Create an object of the outer class. AccessingLocalVar av=new AccessingLocalVar(); av.m1(); } }
    Output: Compile time error: local variable x is accessed from within inner class; needs to be declared final.
Key points: 
If you want to access the local variable within a method local inner class, in this case, the variable must be effectively final. An effectively final variable is a variable whose value does not change once it is initialized. To have an effectively final variable, declare the variable as final. 
Program source code 8:
    package innerClass; public class AccessingLocalVar { public void m1(){ final int x=20; // local variable of m1(). class InnerClass { public void printSum(){ System.out.println(x); // i.e System.out.println(20); at compile time. } } InnerClass ic=new InnerClass(); ic.printSum(); } public static void main(String[] args) { // Create an object of the outer class. AccessingLocalVar av=new AccessingLocalVar(); av.m1(); } }
    Output: 20
Every final variable will be replaced by a value at the time of compilation only. That is 'x' will be replaced by a value 20 at compile time. Hence, we will not get compile time error.

Note: Prior to Java 1.8 version, a local variable must be declared as final if it is accessed inside a local inner class or an anonymous inner class. But from Java 1.8 version, this rule has been changed: the local variable need not be declared final, but it should be effectively final.
Program source code 9:
    package innerClass; public class AccessingTest { int a=20; static int b=30; AccessingTest(){ int c=40; final int d=50; class InnerClass { public void printValue(){ ...... } } InnerClass ic=new InnerClass(); ic.printValue(); } public static void main(String[] args) { AccessingTest obj=new AccessingTest(); } }
Consider the following above code. Which of the following variables can be accessed directly inside the method printValue()?
Ans: We can directly accessed the variables a, b, c, and d inside the printValue(). The output will be 20, 30, 40, and 50. If you are using version prior to Java 1.8 version, you cannot access the variable c. It will generate compile time error.
Program source code 10:
    package innerClass; public class AccessingTest { int a=20; static int b=30; public static void m1(){ int c=40; final int d=50; class InnerClass { public void printValue(){ ....... } } InnerClass ic=new InnerClass(); ic.printValue(); } public static void main(String[] args) { AccessingTest obj=new AccessingTest(); m1(); } }
Consider the above program, which of the following variable we can access directly inside the local inner class?
Ans: The variables b, and d can be accessed directly if you are using version prior to Java 1.8 version. The result will be 30, and 50. But if you are using Java 1.8 version, the result will be 30, 40, and 50.

Final words 

Hope that this article has covered almost all important points related to the topic method local inner class in Java with practical example programs. All the programs are very important to clear concepts. We hope that you have enjoyed this article.
Thanks for reading!
Next ➤ Anonymous Inner Class in Java

⏪ Prev Next ⏩