static Keyword
static keyword is used to indicate that you are making someting static & common for all instances created
static keyword can be used on Java methods, blocks, variables, enum and nested classes. static can also be used inside intertaces. Top level classes and interfaces cannot be static.
class Thing{
static void roll() {
}
}
static variables
static Variables are properties of a class and there will be only one copy of the variable for all instances you create for the class, regardless of how many. This is different from non-static variables which are per instance
static int countOfEmployees=0;
static char flag='C';
static float totalRevenue=0.0;
static List listOfElements;
static Set setOfColors=new HashSet();
Values can be static variable can be modified or updated by other parts of the code
static methods
static methods are methods at the class level. Hence, can be invoked by any instance of the class. Actions done inside the static method are common to all instances.
static void incrementEmployee(){
countOfEmployees++;
}
Most commonly used static method is public static void main(String args[])
Nested static classes
Classes cannot be static at the top class level. However, nested classes can be static.
static class can have the following members:
- static variables
- non-static variables
- static methods
- non-static methods
- enum
static classess have following members as well though not that frequently used
- other static nested classes
- other non-static nested classes
Example for Nested static class
import java.util.ArrayList;
import java.util.List;
public class World {
static class Continent{
int va=10;
static int var=25;
List l=new ArrayList();
void hello() {
System.out.print("Good Morning!!");
}
static String content() {
return "Good words";
}
static class Country{
//members
}
class Island{
//members
}
enum OCEAN{
ATLANTIC, ARCTIC, PACIFIC, INDIAN, SOTHERN, WORLD
}
}
}
static blocks
static block is a block of code marked as static. static block is executed everytime the class is loaded. That is every time, you access a member of the class. static blocks cannot be used inside interfaces.
static usage inside interfaces
static variables, static methods and static enum can be used inside interfaces. static interface and static classes can be also be nested inside interfaces
public interface Ocean {
static int t=0;
static double area() {
return 5000.0;
}
static enum ocean{
ATLANTIC,PACIFIC,INDIAN, ARCTIC,SOUTHERN, WORLD
}
static interface Island{
//members
}
static class archipelago{
//members
}
}