简体   繁体   中英

Java: calling a method on a Constructor

Java constructors can't return a value. Why can then we still call an instance method on a constructor? Eg why is new Foo().bar() legal where bar() is an instance method of class Foo ?

While the constructor doesn't return a value, the expression new Foo() does evaluate to an expression — namely, the reference value of the newly created object.

In fact, that's how Foo var = new Foo() works. There's nothing special going on there: you're declaring a new variable var , and assigning it to the result of some expression. It just so happens that evaluating that expression also creates a new object.

new Foo().bar() is equivalent to (new Foo()).bar() . It evaluates an expression ( new Foo() ), which at compile-time has a static type of Foo , and then performs an operation on the resulting value (invoking the bar() method).

In that regard, it's similar to (a + b) * c , which evaluates an expression ( (a + b) ) and then performs an operation on the resulting value (multiplying it by c ).

Java constructors can't return a value. Why can then we still call an instance method on a constructor?

Constructor not returning anything here in the case new Foo().bar() . The method invoking on Foo class bar() returning something that you are capturing.

Why it is legal to write new Foo().bar() ?

It's 100% legal, since it's equivalent to

Foo foo = new Foo();
foo.bar();

It's the "new" keyword that instantiates the object, not the constructor and it is that object that you are calling foo from. The constructor is just telling the compiler what must be done for the newly instantiated instance.

When you code: new Foo().bar(); the following happens.

  • Create a new instance of Foo
  • The instance will then call Foo's Constructor
  • The instance is then returned.
  • Now bar() is called for the returned instance.

Java Constructor returns the instance of that class. 'new Foo()' is creating object of Foo class and you are calling bar() method of that object. So its completely legal!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM