my dog learned polymorphism*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes new class.method() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "new class.method() " Watch "new class.method() " New topic
Author

new class.method()

Kok Lum Chan
Greenhorn

Joined: Apr 12, 2009
Posts: 10
Hi all,



The above codes are from K&B SCJP6 (Chapter 2).

I have a difficulty understanding the last line. Usually, we do something like below :

why oWhy = new why();
oWhy.flipper();

Why this time it can allocate an object to the heap and calling the method at the same time ?

Any advice is appreciated.
Malte Wannerskog
Ranch Hand

Joined: Jan 06, 2011
Posts: 92

update: fixed


OCPJP (310-065) - 88%
Relja Damnjanovic
Greenhorn

Joined: Feb 19, 2010
Posts: 6

Hi koklum!

The thing you're asking is pretty simple - in the case of the written code the author doesn't need the object instance any more so he/she is using the shorter syntax for the call.

So, in your example you create the object and reference it with a variable oWhy



and then invoke the method on that object



In the book example case, the created object is not assigned to variable, but is directly used only to invoke the method.



After this line this object is unreachable so if we would like to use it again we would have to instantiate it again.

Take look at the chapter dealing with Strings and its methods, you should see more examples like this dealing withe the piping the methods one to another, basically it's a same thing - only here first called method is a constructor, and constructors have different syntax for invocation.



SCJP done, SCWCD on the way!
www.reljadamnjanovic.com
Kok Lum Chan
Greenhorn

Joined: Apr 12, 2009
Posts: 10
Hi Relja,

Thank your for your clear explanation. It make sense to me now.


 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: new class.method()
 
Similar Threads
please answer my query?
tipsmart mock
What will be the output of the following piece of code?
Switch- Case doubt in case expressions.
Reference variable casting