shrini1000 shrini1000 - 25 days ago 21
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
bar()
is an instance method of class
Foo
?

Answer

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

Comments