Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

question about using "new"

 
Paul Chamsay
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I'm just wondering what's the difference of doing this:



as opposed to this



Are there any performance implications? Which "style" is more recommended? Thanks!
 
Dawn Charangat
Ranch Hand
Posts: 249
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"style" 2

owing to readability and hence better maintainability.

Also, if you need to use the instance of "IceCream" for further tasks within your class, you'll need a reference to that object, which you wont get, if you use the first way.
 
Hunter McMillen
Ranch Hand
Posts: 492
Firefox Browser Linux VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
They both do the same thing, your second example is better style because what would happen if you wanted to call another method on new Icecream()?






Hunter.
 
Gregg Bolinger
GenRocket Founder
Ranch Hand
Posts: 15302
6
Chrome IntelliJ IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hunter McMillen wrote:They both do the same thing, your second example is better style because what would happen if you wanted to call another method on new Icecream()?



Hunter.


Well, you can do that if go() returns an instance of IceCream. I'd argue that one method isn't better than the other if all you need to do is instantiate the class and/or call a single method. The whole "what happens when..." is when your tests deem it necessary and you refactor.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic