shrini1000 shrini1000 - 1 year ago 137
Java Question

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? E.g. why is

new Foo().bar()
legal where
is an instance method of class

Answer Source

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).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download