-First use:
so here's a little exemple :
let's say we need to create people profiles, so we'll make a class named profile
and we need that every profile to have an id
public class Profile{
int id;
String name;
public Profile(String name,int id)
{this.name=name;
this.id=id;}
}
the probleme here is : how to make a default id , and every time we create a profile , it will increase and have it's own personal id ??like this :
profile 1 :id=1
profile 2 : id=2
profile 3: id=3
without creating it manually !
To have this we need a static variable ,it means that this Variable will be shared by all the objects from the same class : if this variable equals 1 , it means in all the others objects that have the same class will have it equals 1!
let's write our class to have this
public class Profile{
int id;
String name;
//here is it! the first time it will have 1
static int idIncreaser=1;
public Profile(String name)
{this.id=this.idIncreaser; //so the first time the object will have id=1
this.idIncreaser++; //we'll increase it so the next created object will
// have id=2
this.name=name;
}
}
and about a static method, we make it static if we will use it in the
main Class or we want it to do the same work like our idIncreaser
-Second use: if you have a static variable or a static method, you are able to acces it without the creation of objects, it means that you can do:
int a=Profile.idIncreaser; //note that the 'p' is in uppercase to be able to acces the class !
In General: note that a static variable/method is shared by all the objects of this class, and can be accessible witout the instanciation or creation of any object