How to use the Java static keyword?

In Java, the keyword “static” is used to modify members of a class, such as static variables, static methods, and static code blocks.

  1. Static variables:
    Static variables belong to the class rather than the instance, and their value is shared among all instances. They can be accessed directly through the class name without creating an instance of the class. They are modified using the static keyword.
  2. The class named MyClass has a static variable called myStaticVariable.
  3. The static variable can be accessed through MyClass.myStaticVariable.
  4. Static methods:
    Static methods do not rely on any instance and can be called directly using the class name. They can only access static variables and cannot access non-static variables, because the value of non-static variables is associated with the instance. Keywords: static.
  5. In the class called MyClass, there is a static method named myStaticMethod.
  6. You can call the static method through MyClass.myStaticMethod().
  7. Static block:
    The static block is executed when the class is loaded, and it only runs once. It can be used to initialize static variables or perform other static operations. It is designated with the keyword “static”.
  8. MyClass class with a static block for implementation.
  9. The code in a static block will be executed when the class is loaded, allowing for some initialization operations to be performed within it.

It is important to note that static members can be accessed directly by the class name without the need to create an instance, so there is no need to reference them through an object when accessing them. Static members are associated directly with the class, not with instances of the class.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds