A local class is a class defined within a method of a certain class.
Access modifier not available (private, protected, public) static modifier not available abstract and final modifiers can be used Access to members of outer class
In the code below, you can see that the argument of the method of the outer class, the local variable cannot be accessed unless it is a constant, and that it is automatically made a constant. Also, it can be seen that the instance variables of the outer class can be accessed from the local class even if they are not constants.
class OuterA{ //Outer class
private static int a = 1;
private int b =2;
void methodOuter(final int c, int d) {
final int e =5; int f =6;
//c=10; //c is a constant because it has final. Cannot be reassigned.
//d=10; //At this point, it is not a constant and can be substituted.
//However, doing this confirms that d is a variable, which prevents calls from local classes.
//d++; //Final is added at the time of variable declaration, so if you make this change, you will not be able to call from the local class
//f++;
class A{ //Local class
void method() {
System.out.print(a+" ");
System.out.print(b+" ");
System.out.print(c+" ");
System.out.print(d+" ");
System.out.print(e+" ");
System.out.print(f+" \n"); //「\"n" is a line break
a++;
b++;
//c++;
//d++;
//e++;
//f++;
//c,d,e,f is a constant, but a,b is not a constant
System.out.print(a+" "+b);
}
}
new A().method();
}
}
public class Test3 {
public static void main(String[] args) {
OuterA o = new OuterA();
o.methodOuter(3,4);
}
}
1 2 3 4 5 6
2 3
(1) Instance variables can be called from a local class even if they are not constants.
(2) When calling a method argument and a local variable from a local class, it must be a constant (with final modifier). (If not attached, it is implicitly given)
(3) When the final modifier is implicitly added, it is done at the time of variable declaration, so when calling the variable from the local class, before calling the variable from the local class (using the variable in the local class) If so, do not reassign the value.
(4) When the value is changed (assignment, increment, etc.) after the variable is declared, the variable is confirmed and cannot be called from the local class.
Michiko Yamamoto "Java Programmer Gold SE8" Shoeisha.
Recommended Posts