Win a copy of Head First Agile this week in the Agile forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

how does this work?  RSS feed

 
jay nair
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

the above code just works fine ,
i wanted to know how " new TestServer().logIn();" works?
Is this line instantiating an object ( since its using " new" )
and if yes why is it not assigned to a variable of type TestServer?
 
Kristian Perkins
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by jay nair:



Yes, two new TestServer objects are being created but no variable is being assigned to them, so they are essentially lost and eligible for garbage collection after they return from their respectively invoked methods (since the methods don't assign the instance they run in to any variable either).
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"new TestServer()" is an expression which returns a new TestServer object, whether or not you assign that object to a variable. Most of the time, you create an object and store a reference to it in a variable, but once in a while, the reference is not necessary -- for example, if you need to call one method on the object and then never use it again. This comes up with Threads sometimes, for example: you'll see a line like

new Thread(new MyRunnable()).start();

I note that in your example code, there really should be a variable; otherwise two TestServer objects are being created when only one is actually necessary.
 
Justin Fox
Ranch Hand
Posts: 802
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
basically,

when you define a variable in a method, usually another method can't use it

so therefore, when you set count = 10; in login, count can't use it.

so count uses the instance data defined in class "testserver" for count

instead of login's variable "count".

-Justin-
 
jay nair
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks a lot...
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!