클래스 멤버와 로컬변수 사용


클래스 멤버 사용


람다식 실행 블록은 클래스의 멤버인 필드와 메소드를 제약없이 사용가능

하지만 주의할 것은 this 키워드!!

일반적인 익명 객체 내부에서는 this는 익명 객체의 참조이지만

람다식에서는 실행한 객체의 참조임


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public interface MyFunctionInterface {
    public void method();
}
 
 
public class UsingThis {
    public int outterField = 0;
    
    class Inner {
        int innerField = 10;
        
        void method() {
            MyFunctionInterface fi = () -> {
                //outterField를 참조하기 위한 방법
                System.out.println("outerField : " + outterField);
                System.out.println("outerField : " + UsingThis.this.outterField);
                
                //innerField를 참조하기 위한 방법
                System.out.println("innerField : " + innerField);
                System.out.println("innerField : " + this.innerField);
            };
            fi.method();
        }
    }
}
 
 
public class UsingThisExample {
    public static void main(String[] args) {
        UsingThis usingThis = new UsingThis();
        UsingThis.Inner inner = usingThis.new Inner();
        inner.method();
    }
}
cs



로컬변수 사용


로컬변수는 제한 없이 사용가능

그러나 사용 변수는 final 특성을 가지게 되어 변경 불가능하게 된다.

+ Recent posts