Static Members
Some Basic Question about Static member:
- Why do we need Static members?
- What exactly are Static Variable and Methods?
- How to go about Accessing them?
Why do we need Static members?
There are situations in which the method’s behavior does not depend on the state of an object. So, there will be no use of having an object when the method itself will not be instance specific.
What exactly are Static Variable and Methods?
Variables and methods marked static belong to the class rather than to any particular instance of the class. These can be used without having any instances of that class at all. Only the class is sufficient to invoke a static method or access a static variable. A static variable is shared by all the instances of that class i.e only one copy of the static variable is maintained.
class Animal
{
static int animalCount=0;
public Animal()
{
animalCount+=1;
}
public static void main(String[] args)
{
new Animal();
new Animal();
new Animal();
System.out.println(“The Number of Animals is: “
+ animalCount);
}
}
How to go about Accessing them?
In case of instance methods and instance variables, instances of that class are used to access them.
But static members are not associated with any instances. So there is no point in using the object. So, the way static methods (or static variables) are accessed is by using the dot operator on the class name, as opposed to using it on a reference to an instance.
class Animal
{
static int animalCount=0;
public Animal()
{
animalCount+=1;
}
public static int getCount()
{
return animalCount;
}
}
class TestAnimal
{
public static void main(String[] args)
{
new Animal();
new Animal();
new Animal();
System.out.println(“The Number of Animals is: “
+ Animal.getCount());
/*
Notice the way in which the Static method is
called using the class name followed by static method.
*/
}
}
More Example will be update.