[람다식] Java 람다식 멤버변수, 로컬변수 사용하기(this 사용)

멤버변수

- 클래스 변수라고도 하며 메소드에 선언된 것이 아닌 클래스의 필드에 선언된 변수.

로컬변수

- 메소드가 실행될 때만 사용되는 변수. 메소드 내부에 선언되어 있음.

 

람다식에서 클래스의 멤버변수 사용

- 람다식에서 this는 내부적으로 생성되는 익명객체의 참조가 아닌 람다식을 실행한 객체의 참조이다.

- 바깥 객체와 중첩 객체의 참조를 얻어 필드값을 출력하는 예제.

@FunctionalInterface
public interface MyFunctionalInterface {
    public void method();
}
public class UsingThis {
    public int outterField = 10;

    class Inner{
        int innerField = 20; //Inner 클래스 멤버변수.

        void method(){
            //람다식
            MyFunctionalInterface fi = () -> {
                System.out.println("outterField : "+outterField); //10
                System.out.println("outterField : "+UsingThis.this.outterField); //10

                System.out.println("innerField : "+innerField); //20
                System.out.println("innerField : "+this.innerField); //20
            };
            fi.method();
        }

    }
}
public class TestExample {
    public static void main(String[] args) {
        UsingThis usingThis = new UsingThis();
        UsingThis.Inner inner = usingThis.new Inner();
        inner.method();
    }
}

- 중첩 클래스의 상위 클래스의 멤버변수를 접근하기 위해서는 클래스명.this 키워드로 접근해야함.

- 중첩 클래스의 변수는 this 키워드로 접근 가능. -> 구현하는 익명객체(fi)가 Inner 클래스의 method() 메소드에서 사용되고 있기 때문.

 

람다식에서 로컬변수 사용
@FunctionalInterface
public interface MyFunctionalInterface {
    public void method();
}
public class UsingLocalVariable{
    void method(int arg){
        int localVar = 40; //final 특성을 가짐

        //arg = 30; 주석을 풀면 에러남.
        //localVar = 30; 주석을 풀면 에러남.

        //람다식
        MyFunctionalInterface fi = () -> {
          //로컬변수 읽기
          System.out.println("args : "+arg);
          System.out.println("localVar : "+localVar);
        };
        fi.method();
    }
}
public class TestExample {
    public static void main(String[] args) {
        UsingLocalVariable ulv = new UsingLocalVariable();
        ulv.method(20);
    }
}

- 람다식에서 로컬변수, 매개변수를 사용할때는 final 특성을 가지게 된다.

- 로컬변수를 수정하거나, 매개변수를 수정할 수 없다.(람다식에서 사용될 경우!!!)

댓글

Designed by JB FACTORY