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

Why do we use static keyword? What if we do not use it? When to use static keyword? Please explain with example.

Why do we use static keyword? What if we do not use it? When to use static keyword? Please explain with example. Its quite confusing

1 Answer

Daniel Vargas
Daniel Vargas
29,184 Points

OK, I'll give it a shot.

Let's say we have a class name car with 2 fields: minNumberOfWheels and brand, but one of them is a static field

public class Car {
  public static int minNumberOfWheels = 4;
  private String brand;

 public Car (String brand) {
   this.brand = brand; 
  }

  //getters and setters here
  }
}

So now we can create Car objects:

    Car car1 = new Car("Nissan");
    Car car2 = new Car("Tesla");
    Car car3 = new Car("BMW");

All these 3 cars have different brands, however they share the same value for minNumberOfWheels and If we change that value in one car, all the other cars will get the same change.

So basically a static field is share by all the objects you create from that class.

Craig used a static field MAX_PEZ because all of the pez dispensers will share that max capacity and he made it final so it can not be changed.

Is not mandatory to use static fields. In this case is the best choice (in terms of memory and performance) however, if you chose not to use it your code will still work.

I hope that was helpfull.

Bryan Martinez
Bryan Martinez
2,227 Points

This was a great explanation. Thank you!