There are 4 kinds of static members:
- Static variables
- Static methods
- Static nested classes
- Static blocks
Static variables
Static variables are used to represent metadata — information related to the class itself.
- If you have only data related to a class, use a static variable.
- If the data needs extra processing, use a static method.
- If you have a lot of data that can be grouped together, use a static nested class.
Static members are shared by all objects of the class — if any object modifies the static member, the value changes for all of them. Static members can also be accessed using just the class name with dot notation, without creating an object.
class HondaCity { static long price = 10; int a, b; // the static method below cannot access these, since they aren't static
static double onRoadPrice(String city) { switch (city) { case "delhi": return price + price * 0.1; case "mumbai": return price + price * 0.09; } return price; }}
public class StaticMembers { public static void main(String[] args) { HondaCity n1 = new HondaCity(); HondaCity h2 = new HondaCity(); System.out.println(HondaCity.price); // access static member from the class itself }}Static methods
- They belong to a class
- They are common for all the objects
- They can be called using either the class name or an object name
- Static methods can only access static variables/members
Static nested classes
If you have multiple static methods, you can group them into a static class — its members can then be accessed independently of the outer class.
Note: you cannot use this or super inside a static method or a static class.