• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Static

 
Mike Shn
Ranch Hand
Posts: 149
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is a purpose of static fields and methods in Java?
 
Michael Ernest
High Plains Drifter
Sheriff
Posts: 7292
Netbeans IDE VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A static field or member is maintained once in memory and used by all instances of that class. One way to imagine using this is to think of an instance counter. You could increment it every time an object gets made, and each object would then "know" how many total instances had been created.
A static method can be invoked without ever making an instance of the class that contains it. Best straightforward example: all the methods in the Math class. You don't really need a Math object for anything, so why create one just to make use of its functions ? (You can't make Math objects, anyway, but that's because it's final class).
------------------
Michael Ernest, co-author of: The Complete Java 2 Certification Study Guide
 
Stanley Tan
Ranch Hand
Posts: 243
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For example, imagine you have 20 people with different hair colors. If the hair color were static and one person changed his hair color to blue, then you would have 20 people with blue hair .
 
Richard Boren
Ranch Hand
Posts: 233
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Michael Ernest:
... (You can't make Math objects, anyway, but that's because it's final class).

The reason you cannot instantiate the Math class is becuase it has a private constructor (private Math() {}), not because the class is final. When a class is made final it is saying it cannot be extended which has nothing to do with it being instantiated.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic