In the concepts of object oriented programming, classes have two kind of attributes and methods :
- the attributes and methods of the class
- the attributes and methods of the object, the instance of the class
The
static modifier is designed for the members specific to the class.
The main advantage of static members is that they are accessible from everywhere in an application without creating an instance of the class.
Example :
Code:
public class Account {
private static int number = 0;
private static double total = 0;
private double balance;
public Account(double balance) {
this.balance = balance;
insert(balance);
}
private static void insert(double balance) {
number++;
total = total + balance;
}
public double showBalance() {
return balance;
}
public static double showAverage() {
return total / number;
}
public static double showTotal() {
return total;
}
public static int showCounter() {
return number;
}
}
In my example, I will be able to know the number of instances of Account already created
just by running the statement
Account.showCounter() in my application.
For nested classes, static members would have no meaning because nested classes have no existence without their host classes and they are generally built for a specific limited usage.