Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Giorgi Kiknadze
Courses Plus Student 2,768 PointsStatic keyword?
What does exactly do static keyword? I though that it is for REPL and we can get info about class without creating it, but I think it's not right.
1 Answer
Steve Hunter
57,712 PointsHI there,
Yes, a static variable or method can be called without instantiating the class. Also, a static variable is shared across all instances of that class - it only has memory allocated once.
So, you could define a static member variable that is initialised to zero:
static int numberOfInstances = 0;
Then, inside the constructor, it can be incremented:
class MyClass{
static int numberOfInstances = 0;
public MyClass(){
// do the constructor stuff
numberOfInstances++;
}
}
Now, we can access that member variable (which is the same member variable for all instances of MyClass which will tell us how many objects of MyClass exist.
The key thing is memory efficiency. A static variable only gets allocated one slot of memory irrespective how many instances of the class exist, they all point to that static variable.
I hope that makes sense!
Steve.