2012-12-23 3 views

답변

9

내부 클래스 내에서 둘러싸는 클래스의 암시 적 인스턴스에 액세스하는 방법입니다. 예를 들어 :

모든 어휘 둘러싸 예 (§8.1.3)가 될 수 있습니다

public class Test { 

    private final String name; 

    public Test(String name) { 
     this.name = name; 
    } 

    public static void main(String[] args) { 
     Test t = new Test("Jon"); 
     // Create an instance of NamePrinter with a reference to the new instance 
     // as the enclosing instance. 
     Runnable r = t.new NamePrinter(); 
     r.run(); 
    }  

    private class NamePrinter implements Runnable { 
     @Override public void run() { 
      // Use the enclosing instance's name variable 
      System.out.println(Test.this.name); 
     } 
    } 
} 

는 "this 자격"표현의 내부 클래스와 둘러싸는 인스턴스에 대한 이상 Java Language Specification section 8.1.3section 15.8.4을 참조하십시오 this 키워드를 명시 적으로 한정하여 참조됩니다.

CClassName으로 표시하는 클래스로 지정하십시오. n을 정수로 사용하여 C이 정규 표현식이 나타나는 클래스의 어휘를 둘러싸는 n 번째 클래스입니다.

ClassName.this 형식의 표현식 값은 어휘 적으로 이것을 감싸는 n 번째 인스턴스입니다.

식의 유형은 C입니다.

+0

존이있는 경우, C#에서 비슷한 일이? –

+0

@AdamLee : C#의 중첩되지 않는 클래스는 Java의 내부 클래스처럼 작동하지 않습니다. 함축적 인 인스턴스가 없습니다. 그들은 Java에서 정적 중첩 클래스처럼 작동합니다. –

1

내부 클래스에서이 클래스를 제한하는 TestClass 인스턴스에서 instante 메서드를 호출하고 있습니다.

1

클래스의 내부 클래스에서 사용할 수 있습니다. 외부 클래스를 참조합니다. 예를 들어

당신이 클래스 고양이

public class Cat { 

private int age; 
private Tail tail; 

public Cat(int age) { 
    this.age = age; 
    this.tail = new Tail(); 
} 

class Tail { 

    public void wave() { 
     for(int i = 0; i < Cat.this.age; i++) { 
      System.out.println("*wave*"); 
     } 
    } 

} 

public Tail getTail() { 
    return tail; 
} 

/** 
* @param args 
*/ 
public static void main(String[] args) { 
    new Cat(10).getTail().wave(); 
} 

} 
관련 문제