Development Tip

"object.new"는 어떻게 작동합니까?

yourdevel 2020. 11. 18. 21:35
반응형

"object.new"는 어떻게 작동합니까? (Java에 .new 연산자가 있습니까?)


나는 오늘 Accelerated GWT (Gupta)-page 151 을 읽는 동안이 코드를 보았습니다 .

public static void getListOfBooks(String category, BookStore bookStore) {
    serviceInstance.getBooks(category, bookStore.new BookListUpdaterCallback());
}
public static void storeOrder(List books, String userName, BookStore bookStore) {
    serviceInstance.storeOrder(books, userName,    bookStore.new StoreOrderCallback());
}

새로운 대원들은 거기서 무엇을하고 있습니까? 나는 그런 구문을 본 적이 없습니다. 누구든지 설명 할 수 있습니까?

누구든지 자바 사양에서 이것을 어디에서 찾을 수 있는지 알고 있습니까?


그들은있어 내부 (중첩 된 비 정적) 클래스 :

public class Outer {
  public class Inner { public void foo() { ... } }
}

넌 할 수있어:

Outer outer = new Outer();
outer.new Inner().foo();

또는 간단히 :

new Outer().new Inner().foo();

그 이유 Inner는 외부 클래스의 특정 인스턴스에 대한 참조 가 있기 때문입니다 . 이에 대한 더 자세한 예를 들어 보겠습니다.

public class Outer {
  private final String message;

  Outer(String message) {
    this.message = message;
  }

  public class Inner {
    private final String message;

    public Inner(String message) {
       this.message = message;
    }

    public void foo() {
      System.out.printf("%s %s%n", Outer.this.message, message);
    }
  }
}

다음을 실행하십시오.

new Outer("Hello").new Inner("World").foo();

출력 :

Hello World

참고 : 중첩 클래스도 가능합니다 static. 그렇다면 this외부 클래스에 대한 암시 적 참조 가 없습니다 .

public class Outer {
  public static class Nested {
    public void foo() { System.out.println("Foo"); }
  }
}

new Outer.Nested.foo();

More often than not, static nested classes are private as they tend to be implementation details and a neat way of encapsulating part of a problem without polluting the public namespace.


BookListUpdaterCallback and StoreOrderCallback are inner classes of BookStore.

See The Java Tutorial - http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html and http://docs.oracle.com/javase/tutorial/java/javaOO/innerclasses.html


I haven't seen this syntax before either, but I think it will create an inner class of BookStore.

참고URL : https://stackoverflow.com/questions/2863157/how-does-object-new-work-does-java-have-a-new-operator

반응형