-
Notifications
You must be signed in to change notification settings - Fork 0
Java의 Closure
Younghoo Kim edited this page Aug 12, 2015
·
3 revisions
##Inner Class의 Closure
inner Class의 경우 외부 환경에 대한 레퍼런스를 가지고 있기 때문에
variable x와 y에 대해 접근이 가능하다.
variable y의 경우 field variable로 선언되었기 때문에
프로세스가 수행되는 동안에는 참조값이 유지된다.
따라서 innerClass에서 variable y에 대해 참조 및 값의 변경이 가능하다.
하지만 foo() 메소드 내부에 있는 variable x는 foo() 메소드 수행
이후 값이 소멸되는게 정상이지만 JAVA에서는 inner Class에서
variable x에 대한 접근을 가능하게 하고 있다.
(정확히는 생성된 익명 객체가 variable x의 복사본을 가지게 된다.)
하지만 제약조건은 존재한다.
그것은 바로 final로 선언되어야 한다는 점이다.
예를 들어, variable x가 btn.setActionListener() 메소드 이후에
값이 변경되었다면 inner Class는 variable의 어떤 값을 참조해야 하는
지에 대한 모호함이 발생하기 때문이다.
package com.hoo;
public class Main {
private String y = "world";
public void foo() {
final String x = "hello";
final int y = 1;
Button btn = new Button();
btn.setActionListener(new Button.ActionListener() {
@Override
public void actionPerformed() {
System.out.println("x : " + x); // Closure
System.out.println("y : " + y);
}
});
}
public static void main(String[] args) {
Main obj = new Main();
obj.foo();
}
}
package com.hoo;
/**
* ClosureExample
* com.hoo
* Created by Hoo on 2015. 8. 13..
*/
public class Button {
ActionListener listener;
interface ActionListener {
public void actionPerformed();
}
public void setActionListener(ActionListener listener) {
this.listener = listener;
}
}