Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Sowm Herur
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
Pie
Posts: 49411
62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
Bartender
Posts: 1277
10
Eclipse IDE Google Web Toolkit Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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"
 
Sowm Herur
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
Rancher
Posts: 42968
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
salvin francis
Bartender
Posts: 1277
10
Eclipse IDE Google Web Toolkit Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic