chapter14. 람다식. 


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


14.1.1 클래스의 멤버 사용

- 람다식 실행 블록에는 클래스의 멤버인 필드와 메소드를 제약 없이 사용할 수 있다.

- 람다식 실행 블록내에서 this는 람다식을 실행한 객체의 참조이다.




함수적 인터페이스

1
2
3
4
5
6
package sec04.exam01_field;
 
public interface MyFunctionalInterface {
    public void method();
//메소드가 하나만 정의되어있기 때문에 함수적 인터페이스
}



실행 클래스

1
2
3
4
5
6
7
8
9
package sec04.exam01_field;
 
public class UsingThisExample {
    public static void main(String... args) {
        UsingThis usingThis = new UsingThis();
        UsingThis.Inner inner = usingThis.new Inner();
        inner.method();
    }
}
cs




 this 사용

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package sec04.exam01_field;
 
public class UsingThis {
    public int outterField = 10;
 
    class Inner {
        int innerField = 20;
 
        void method() {
            //람다식, 함수적 인터페이스에 매개값이 없으므로 ()
            MyFunctionalInterface fi= () -> {
                System.out.println("outterField: " + outterField); // 10
                // 바깥 객체의 참조를 얻기 위해서는 클래스명.this를 사용
                System.out.println("outterField: " + UsingThis.this.outterField + "\n");//10
                
                System.out.println("innerField: " + innerField); // 20
                // 람다식 내부에서 this는 Inner 객체를 참조
                System.out.println("innerField: " + this.innerField + "\n"); // 20
            };
            fi.method(); // 함수적 인터페이스
        }
    }
}
cs






14.4.2 로컬 변수 사용

- 람다식은 함수적 인터페이스의 익명 구현 객체를 생성한다.

- 람다식에서 사용하는 외부 로컬 변수는 final 특성을 갖는다 

// 매개 변수 또는 로컬 변수를 람다식에서 읽는 것은 허용되지만,

// 람다식 내부 또는 외부에서 변경할 수 없다.



함수적 인터페이스

1
2
3
4
5
package sec04.exam02_local_variable;
 
public interface MyFunctionalInterface {
    public void method();
}
cs

실행 클래스

1
2
3
4
5
6
7
8
package sec04.exam02_local_variable;
 
public class UsingLocalVariableExample {
    public static void main(String... args) {
        UsingLocalVariable ulv = new UsingLocalVariable();
        ulv.method(20);
    }
}
cs

 




Final 특성을 가지는 로컬 변수

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package sec04.exam02_local_variable;
 
public class UsingLocalVariable {
    void method(int arg) {  //arg는 final 특성을 가짐
        int localVar = 40;     //localVar는 final 특성을 가짐
        
        //arg = 31;          //final 특성 때문에 수정 불가
        //localVar = 41;     //final 특성 때문에 수정 불가
        
        //람다식
        MyFunctionalInterface fi= () -> {
            //로컬변수 사용
            System.out.println("arg: " + arg); 
            System.out.println("localVar: " + localVar + "\n");
        };
        fi.method();
    }
}
cs



Posted by 너래쟁이
: