[JAVA] static modifier

What is a static modifier?

The static modifier is primarily used to access methods and variables directly without instantiating it into a class.

Methods with these statics are called static methods, and variables are called static variables.

There are many ways to use the static modifier, including the following: -How to use static in inner class ・ How to use constants in static final -How to use static import to simplify the reference of static members of external classes

What is a static modifier?

Define static members Adding the static modifier to a member of a class makes it accessible without instantiating the class. Specifically, it can be accessed in the format of (class name.member name). Such members are static members Or it is called a static field static method according to each member. For example, the following defines and calls the hoge field foobar method as a static member.

package com.example.mynavi.modifier;
 
public class ModStatic {
    static String hoge = "Static field";
    static void foobar() {
      System.out.println("Static method");
    }
 
  public static void main(String[] args) {
    System.out.println(ModStatic.hoge); //Result: Static field
    ModStatic.foobar(); //Result: Static method
  }
}

When the static modifier is removed from hoge and hoober, the character part must be written as follows.


ModStatic ms = new ModStatic(); //Instantiation required
  System.out.println(ms.hoge);
  ms.foobar();

Recommended Posts

static modifier
static
About static
final modifier
JAVA learning history final modifier and static modifier
Access modifier [Java]
Java static story
Static uncle's counterattack
java final modifier