- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Can a method local inner class access the local final variables in Java?
Yes, we can access the local final variables using the method local inner class because the final variables are stored on the heap and live as long as the method local inner class object may live.
Method Local Inner Class
- A local inner class instance can be delivered as an argument and retrieved from the methods and it is available inside a valid scope.
- The only limitation in method local inner class is that a local parameter can be executed only when it is defined as final.
- The method executing the local parameters can be called after the execution of the method, within which the local inner class was declared. As a result, the local parameters will no longer retain their values.
- The values must be fixed before creating the local inner class object. If required, a non-final variable can be copied into a final variable which is subsequently executed by the local inner class.
Example
class MainClassTest { private int x = 10; public void sampleMethod() { final int y = 20; class MethodLocalInnerClassTest { public void accessMainClassVar() { System.out.println(x); // accessing the final variable System.out.println(c); } } MainClassTest mainTest = new MethodLocalInnerClassTest(); mainTest.accessMainClassVar(); } } // Test.java public class Test { public static void main(String args[]) { MainClassTest test = new MainClassTest(); test.sampleMethod(); } }
Output
10 20
Advertisements