The static modifier for creating class methods and variables
Previous | Home | Next |
Static Variables:
The static key word is used to create variables that will exist independently of any instances created for the class.
Static Methods:
The static key word is used to create methods that will exist independently of any instances created for the class.
Static variable:
Only one copy of the static variable exists regardless of the number of instances of the class.
Static variables are also known as class variables ,local variables cannot be declared static
Static Method:
Static methods do not use any instance variables of any object of the class they are defined in.
Static methods take all the data from parameters and compute something from those parameters,
with no reference to variables.
Note:Class variables and methods can be accessed using the class name followed by a dot and the name of the variable or method.
public class Counter
{
private static int Instances = 0;
protected static int getCount() {
return Instances;
}
private static void addInstance() {
Instances++;
}
InstanceCounter() {
InstanceCounter.addInstance();
}
public static void main(String[] arguments) {
System.out.println("Starting with " +
InstanceCounter.getCount() + " instances");
for (int i = 0; i < 500; ++i){
new InstanceCounter();
}
System.out.println("Created " +
InstanceCounter.getCount() + " instances");
}
}
Previous | Home | Next |