How to use static in java (for beginners)?
Often, people who just start programming in java, have hard time figuring out how and when to use static variables.
So, imagine you have a car manufacturing software and at some point, when you want to produce a car, in your code, you call “Car car = new Car();”
And at some point you would like to know how many cars have been produced.
How would you implement this functionality?
Static variable comes in handy. You declare static field carCount in your Car class and increase it every time constructor is called.
class Car {
static int carCount= 0;
public Car(){
carCount++; //increasing every time a new Car is created
}
}Static field carCount gets created and initialized only once (explained below), but it is updated every time a object of a type Car is created (carCount++) . So if you create 1000 cars, there would be only one carCount variable.
And when you need to access carCount variable, you don’t need to create an object of Car class, you just type Car.carCount.
So what if you didn’t use static for carCount field, and declared it like this:
class Car {
int carCount= 0;
public Car(){
carCount++;
}
}Well, each time you create a car (object of a type Car), a new carCount variable would be created and set to 0 and increased to 1 in constructor, so if you create 1000 car objects, there would be a 1000 carCount variables, each with value of 1. Needles to say, this makes that approach unsuitable for counting the cars produced.
So, anything that is declared static, belongs to the whole class, not to any particular instance (object) of the class.
A class’s static initialization normally happens before the first time an instance of the class (object) is created, or a static method of the class is invoked,
or a static field of the class is assigned… There other ways to force static initialization using Class.forName but that is out of scope of this simple tutorial.
Check out my apps on Google Play Store or Amazon App Store