GeeCON Prague 2014*
The moose likes Java in General and the fly likes Creating a RANDOM_NUM_GENERATOR instance of Random class even though the Random class is static. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Java in General
Bookmark "Creating a RANDOM_NUM_GENERATOR instance of Random class even though the Random class is static." Watch "Creating a RANDOM_NUM_GENERATOR instance of Random class even though the Random class is static." New topic
Author

Creating a RANDOM_NUM_GENERATOR instance of Random class even though the Random class is static.

Sowm Herur
Ranch Hand

Joined: Jul 07, 2008
Posts: 32

We are creating a RANDOM_NUM_GENERATOR instance of Random class even though the Random class is static.Why is it so?

Please explain

private static Random RANDOM_NUM_GENERATOR = new Random();
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39053
    
  23
You are using the same instance of Random in every instance. I suggest you mark that Random instance final. Then you can't change it by mistake.
Sowm Herur
Ranch Hand

Joined: Jul 07, 2008
Posts: 32

But my question in this case a static variable which is declared doesn't require an instance to be created?
Then why are they creating an instance of the Random_Generator?
salvin francis
Ranch Hand

Joined: Jan 12, 2009
Posts: 928

Random class is static
is it ?

java.util.Random

I think you are a bit confused here,

Its your Variable thats static, not the class.

So when you say :



What you mean is that "A" is a Class, "aObj" is a static variable that points to an Object of "A"


My Website: [Salvin.in] Cool your mind:[Salvin.in/painting] My Sally:[Salvin.in/sally]
Sowm Herur
Ranch Hand

Joined: Jul 07, 2008
Posts: 32

Ok i understand now but why are we creating an instance of the static variable?

Static variables doesn't have any instance rite?
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 42031
    
  64
Sowm Herur wrote:Ok i understand now but why are we creating an instance of the static variable?

Static variables doesn't have any instance rite?

Wrong. All variables reference an object instance, it's just that for static variables, there's only a single instance for all objects of a class, while for non-static variables there's an object for each and every instance of that class.


Ping & DNS - my free Android networking tools app
salvin francis
Ranch Hand

Joined: Jan 12, 2009
Posts: 928

Sowm Herur wrote:why are we creating an instance of the static variable?

We are Not

We are creating an instance of the Random class, and assigning it to our static variable.
 
GeeCON Prague 2014
 
subject: Creating a RANDOM_NUM_GENERATOR instance of Random class even though the Random class is static.