ByteBrawl - Static - Non Access Modifiers - Encapsulation

Non Access Modifiers - Static

The static modifier indicates that the member of a class belongs to the class itself, rather than to any specific instance of the class. This means that static members can be accessed without creating an instance of the class, which is useful for global data or utility functions that don't rely on instance-specific data. However, top-level classes cannot be declared static, only inner classes can. Let's see an example:

StaticExample.java

Main.java

As you can see, we can access the static variable counter directly through the class name without creating an instance of StaticExample. Additionally, both example1 and example2 share the same static variable secret, so changing it through one instance affects the other. We also saw that we can access static variables within instance methods and that static members can be private too.