Java Local inner classA class i.e., created inside a method, is called local inner class in java. Local Inner Classes are the inner classes that are defined inside a block. Generally, this block is a method body. Sometimes this block can be a for loop, or an if clause. Local Inner classes are not a member of any enclosing classes. They belong to the block they are defined within, due to which local inner classes cannot have any access modifiers associated with them. However, they can be marked as final or abstract. These classes have access to the fields of the class enclosing it. If you want to invoke the methods of the local inner class, you must instantiate this class inside the method. Java local inner class exampleLocalInner1.java Test it NowOutput: 30 Internal class generated by the compilerIn such a case, the compiler creates a class named Simple$1Local that has the reference of the outer class. Rule: Local variables can't be private, public, or protected.Rules for Java Local Inner class1) Local inner class cannot be invoked from outside the method.2) Local inner class cannot access non-final local variable till JDK 1.7. Since JDK 1.8, it is possible to access the non-final local variable in the local inner class.Example of local inner class with local variableLocalInner2.java Test it NowOutput: 50 Next TopicStatic Nested class |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India