How does “object.new” work? (Does Java have a .new operator?)

后端 未结 3 1469
甜味超标
甜味超标 2020-12-07 13:31

I came across this code today whilst reading Accelerated GWT (Gupta) - page 151.

public static void getListOfBooks(String category, BookStore bookStore) {
           


        
相关标签:
3条回答
  • 2020-12-07 13:45

    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

    0 讨论(0)
  • 2020-12-07 13:48

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

    0 讨论(0)
  • 2020-12-07 13:58

    They're inner (nested non-static) classes:

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

    You can do:

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

    or simply:

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

    The reason for this is that Inner has a reference to a specific instance of the outer class. Let me give you a more detailed example of this:

    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);
        }
      }
    }
    

    and run:

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

    Outputs:

    Hello World
    

    Note: nested classes can be static too. If so, they have no implicit this reference to the outer class:

    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.

    0 讨论(0)
提交回复
热议问题