#
"static" keyword in Java
This tutorial explains to you how static
keyword in Java.
#
"static" keyword in Java - theory
When a Java variable is "static":
- that variable has the same value for all the objects instantiated using this class
- the value of the variable is kept in one
heap
zone (the other objects keep references to that heap zone) - your program is memory efficient
Info
When an object modify a static variable value, all the objects generated from the same class will keep that new value of the variable.
When a Java method is "static":
- that method can change/access only "static" variables;
- a static method belongs to the class rather than object of a class.
When a Java block is "static":
- it defines some static variable for that class
- it runs when the class is loaded
#
"static" keyword in Java - example
Here is an example of using the static keyword in Java:
Car.java
public class Car {
float speed;
String colour;
static String owner = "Calgary Taxi Company";
//Constructor
public Car() {
colour = "";
speed = 0;
}
//Constructor
public Car(String colour, float speed) {
this.colour = colour;
this.speed = speed;
}
//static method
static void setOwner(String newOwner){
owner = newOwner;
}
//static method
static String getOwner(){
return owner;
}
//Getters & Setters
public float getSpeed() {
System.out.println("The speed of the Car is "+ speed +" km/h");
return speed;
}
public void setSpeed(float speed) {
System.out.println("The speed of the Car is set at "+speed+" km/h");
this.speed = speed;
}
}
MainApp.java
public class MainApp {
public static void main(String [] args) {
Car car1 = new Car("red",30);
Car car2 = new Car("green",30);
System.out.println("The owner of the Car1 is "+Car.getOwner()+".");
Car.setOwner("Toronto Taxi Company");
System.out.println("The owner of the Car2 is "+Car.getOwner()+".");
//Not good, but you can access the static values like this:
System.out.println("The owner of the Car1 is "+car1.getOwner()+".");
System.out.println("The owner of the Car2 is "+car2.getOwner()+".");
}
}
When you run the code you will see the following result :
The owner of the Car1 is Calgary Taxi Company.
The owner of the Car2 is Toronto Taxi Company.
The owner of the Car1 is Toronto Taxi Company.
The owner of the Car2 is Toronto Taxi Company.
Process finished with exit code 0