• Post Reply Bookmark Topic Watch Topic
  • New Topic

static members!!  RSS feed

 
Brian Smith
Ranch Hand
Posts: 232
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi folks,
i am wondering why static variable or method does not need an intance of a class where they are defined to access them? i.e, if a variable and method are static, we could like this:
classname.static valriable; WHY?
 
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
Why? Because!
Static variables are shared among all the instances of a class, and therefore exist outside of any one instance. The classic example is something like

The static variable counts the number of Cows that are created. The method getTotalNumber() tells you how many Cows. You call it like

It would be silly to have to create another Cow just to find out how many Cows there are, right? It makes sense to ask how many there are even if you don't have a reference to a single one.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!