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 trialMitchell Smit
9,219 PointsStatic vs. Non-Static. Can someone give a clear difference between static and non- static, maybe a real life example?
Why is this useful?
1 Answer
Steve Hunter
57,712 PointsHi Mitchell,
A static
variable is a class-wide variable so every instance of the class holds the same value in its static
variable.
You could use it in a constructor to count how many instances exist, for example:
public class Fiction{
public static int noOfInstances;
public Fiction(){
this.noOfInstances += 1;
}
}
Every instance of Fiction
will have a member variable called noOfInstances
which will contain the same value at all times. That value will equal the number of times the constructor has been run.
I hope that helps.
Steve.
Mitchell Smit
9,219 PointsMitchell Smit
9,219 PointsThanks for the answer its more clear to me now
Steve Hunter
57,712 PointsSteve Hunter
57,712 Points- glad to have helped.