티스토리 뷰
- 기본 closue 예
public static void main(String[] args) {
//함수 외부에 있는 변수(nonlocal variable, free variable)을 참조하도록 영역?을 넘어 덮어버리기(close) 때문에 closure라고 부름.
//java8부터 final 생략가능하지만, 변경하면 안 됨 --> effectively final.
//변경하는 코드가 들어가면 컴파일 오류 발생(Local variable factor defined in an enclosing scope must be final or effectively final)
//나중에 실행되거나, 전혀 다른 쓰레드에서 실행될 수 있기 때문???
int number = 100;
testClosure(new Runnable() {
@Override
public void run() {
number = 101; //--> 컴파일오류발생(Local variable number defined in an enclosing scope must be final or effectively final)
System.out.println(number); //--> 컴파일오류발생
}
});
testClosure(() -> System.out.println(number)); //--> 컴파일오류발생
number = 101;
}
private static void testClosure(final Runnable runnable){
runnable.run();
}
- Lamda expression에서의 closure 확장. shadowing예제
public class ClosureSample2 {
private int number = 999;
public static void main(String[] args) {
new ClosureSample2().test();
}
private void test(){
int number = 100;
testClosure(new Runnable() {
@Override
public void run() {
System.out.println(number); //-->100
// System.out.println(this.number); //-->오류. 여기 this는 annonymous class인 Runnable object를 가리키게 됨.
System.out.println(ClosureSample2.this.number); //-->999
// System.out.println(toString("staic")); //--> 오류.
//anonymous class가 가지고 있는 메소드(상속한 메소드 포함)와 이름이 동일한 외부 메소드에 접근할 경우 shadowing이 발생한다.
}
});
testClosure(() -> System.out.println(number)); //-->100
testClosure(() -> System.out.println(this.number)); //-->999. Lamda 자체는 scope 없으므로 scope이 object로 확장됨.(rexical scope = static scope.)
testClosure(() -> System.out.println(toString("static"))); //Lamda expression에서는 shadowing이 발생하지 않음
}
private static void testClosure(final Runnable runnable){
runnable.run();
}
}
# Hiding : 상속관계 클래서 사이에서 동일한 이름의 member 변수와 local 변수 사이에서 발생.
# Shadowing : 같은 클래스 내에서 동일한 이름의 member 변수와 local 변수 사이에서 발생.
public class HidingVarParent {
static int x = 10;
int y = 20;
}
public class HidingVarChild extends HidingVarParent {
// subclass hides superclass variables with same name
static int x = 30;
int y = 40;
}
public class Shadowing {
static int x = 10;
int y = 20;
public void methodOne(int x, int y){
System.out.println(x); //30
System.out.println(y); //40
System.out.println(Shadowing.x); //10, accessing hidden static variable using class name.
System.out.println(this.y); //20, accessing hidden non-static variable using this keyword.
}
public static void main(String[] args){
new Shadowing().methodOne(30, 40);
HidingVarChild child = new HidingVarChild();
System.out.println(child.x); //30
System.out.println(child.y); //40
HidingVarParent parent = child; // casting from subclass to superclass
System.out.println(parent.x); //10
System.out.println(parent.y); //20
}
}
- Total
- Today
- Yesterday