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

Java Java Objects Harnessing the Power of Objects Constants

Mitchell Smit
Mitchell Smit
9,219 Points

Static 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

Hi 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
Mitchell Smit
9,219 Points

Thanks for the answer its more clear to me now

:+1: :smile: - glad to have helped.