What does the word 'static' mean in Java?
sobes.tech AI
Answer from AI
The static keyword in Java is used to control access to class members (fields and methods) and their lifecycle.
-
Static fields (class variables): Belong to the class, not to an instance. There is only one copy of a static field for all objects of the class. They are initialized when the class is loaded into memory.
public class Example { static int count = 0; // Static field }Access to static fields is done through the class name:
Example.count. -
Static methods (class methods): Also belong to the class, not to an instance. They can be called without creating an object of the class. Static methods do not have access to non-static fields or non-static methods of the class because an instance of the object is needed for their existence.
public class Example { static void display() { // Static method System.out.println("This is a static method."); } }Call a static method:
Example.display(). -
Static initialization blocks: Used to initialize static fields or perform other actions when the class is loaded for the first time. They are executed once.
public class Example { static { // Static initialization block System.out.println("Class Example loaded."); } } -
Static inner classes: An inner class marked as
staticdoes not have an implicit reference to the outer (enclosing) class. It can be created without an instance of the outer class.public class Outer { static class Inner { // Static inner class // ... } }Creating an instance of a static inner class:
Outer.Inner inner = new Outer.Inner();
Overall, static means that a class member is associated with the class itself, not with its specific instance.