A static keyword in Java can be used in:
Let us take the example to Human class to understand static keyword in variables :
String name; int age; public Human() { } public Human(String name, int age) { this.name = name; this.age = age; }
class Human }
Now, let us create two objects of Human class in the Main class.
String name; int age; public Human() { } public Human(String name, int age) { this.name = name; this.age = age; }
}
public static void main(String[] arg) { Human human1 = new Human("Joe",30); Human human2 = new Human("Paul",54); }
}
So, what happens in the above example is, two objects human1 and human2 is created and values are assigned to it.
So, for both human1 and human2, individual spaces are created for name and age.
Now, let's say we need a property which is common to all Humans. Say the property is noOfLegs(i.e. Number of legs). And as we all know Humans have 2 legs, there is no need to create noOfLegs variables for each object. Rather, there can be a single variable named noOfLegs in the class level itself. So that the memory doesn't gets wasted.
It should look something like the below diagram :
As seen in the above diagram, noOfLegs variable contains a common value which both human1 and human2 objects uses.
Now, to make noOfLegs variable common across all the objects of Human class, we need to mark it as static. So that it doesn't become specific to a class but is directly specific to a class.
Let us use it with the Human class :
String name; int age; static int noOfLegs; // Static variable public Human() { } public Human(String name, int age) { this.name = name; this.age = age; }
class Human }
Now, let us create two objects of Human class in the Main class.
class Human { String name; int age; public static int noOfLegs; // Static variable public Human() { } public Human(String name, int age) { this.name = name; this.age = age; } } class MyApplication { public static void main(String[] arg) { Human human1 = new Human("Joe",30); Human human2 = new Human("Paul",54); Human.noOfLegs = 2; // No object is needed to access a static variable. System.out.println(Human.noOfLegs); } }
In the above example we have declared noOfLegs static.
static int noOfLegs;
Now, the most important thing to note is, we have directly accessed noOfLegs using the class name and assigned it with value 2.
Human.noOfLegs = 2;
But don't you think a variable needs to be accessed using an object of the class.
So, in this case it doesn't happens because noOfLegs is a class variable and has got nothing to do with an object. Rather all the objects can access that common value.
Similar logic applies for methods. If a method is declared as static, it would be specific to a class and you won't need an object to access them.
Also, a static method can access a static variable.