Static in Java

Tram Ho

Static keyword in java:

  • The static keyword is used for better memory management and it can be accessed directly through the class without instantiation.
  • The static keyword belongs to the class, not to the instance of the class.
  • Static keyword with variables, methods, blocks, nested classes.

Static use cases:

  1. Static variables (static variables) : then that variable is called a static variable, or a static variable.
  2. Static methods (static methods) : then that method is called static method.
  3. Static blocks (static blocks) : used to initialize static data members.
  4. Static class (static class) :
    • A class can be made static only if it is a nested class.
    • A nested static class can be accessed without an object of the outer class.
  5. Import static : allows to import static members (static members) of a class or package into another class and then use them as members of that class.

1. Static variables (static variables) in Java:

  • Static variable can be used as a common property, to share data for all objects (or instances) of that class and that helps the program save more memory.

2. Static methods (static methods):

Some features:

  • A static method belongs to the class, not the object of the class.
  • A static method can be called without instantiating a class.
  • A static method can access a static variable and can change its value.
  • A static method can only call another static method, not a non-static method.
  • A static method cannot use the this and super keywords.
  • Users cannot override static methods in Java.

3. Static blocks (static blocks):

  • The static block is used to initialize or change the value of static variables.
  • It is executed before the main method at class load time.
  • A class can have multiple static blocks .

4. Static class (static class):

  • A class can be made static only if it is a nested class.
  • A nested static class can be accessed without an object of the outer class.

5. Import static in Java:

  • Java allows importing static members of a class or package into another class.

References:

https://github.com/hoangtien2k3qx1/java/tree/main/src/java/Static

Share the news now

Source : Viblo