Local in the sense something which is defined inside an init block, a static block, a method or a constructor. All rules and regulations do apply here as well and it cannot go beyond its block.
Rule – when we are using local variables of a function within local class then it must be final.
For example: (TempLocalClass.java)
package com.dev21century;
public class TempLocalClass {
int x=10;
static int y=20;
void display()
{
final int p=30;
class Inner
{
public void show()
{
System.out.println("p = "+p);
System.out.println("x = "+x);
System.out.println("y = "+y);
}
}
Inner inner=new Inner();
inner.show();
}
public static void main(String[] args) {
TempLocalClass temp=new TempLocalClass();
temp.display();
}
}
In above program try to remove final keyword and recompile, it will not be compiled successfully.
In above program we have invoked the show() method inside display method, now how we will invoke it outside its method, because we cannot create an object of local class outside of the method. The solution for this problem is, create an interface with show() method and implement it in local class and return its reference variable. Like this:
Alter above program as follows:
package com.dev21century;
interface My
{
public void show();
}
public class TempLocalClass {
int x=10;
static int y=20;
My display()
{
final int p=30;
class Inner implements My
{
public void show()
{
System.out.println("p = "+p);
System.out.println("x = "+x);
System.out.println("y = "+y);
}
}
My my = new Inner();
return my;
}
public static void main(String[] args) {
TempLocalClass temp = new TempLocalClass();
My my = temp.display();
my.show();
}
}
Output:
Same as above.
Here compiler will create separate .class files for all local classes and name them something like Outer$1InnerClassName.class, Outer$2InnerClassName.class etc. In our program the compiler will create .class file name as TempLocalClass$1Inner.class.
No comments:
Post a Comment