0
0

More than 3 years have passed since last update.

Java static修飾子

Posted at

1,static修飾子とは

クラスのフィールド変数やメソッドをそのクラス内で共有します。
staticがついているものはそのクラスが所有することになります。

2,ソースコード

Main.java
public class Main {

    public static void main(String[] args) {

        // static = modifier. A single copy of a variabole/method is created and shared.
        // the class "owns" the static member

        Friend friend1 = new Friend("hiro");
        Friend friend2 = new Friend("tato");
        Friend friend3 = new Friend("yoshi");
        Friend friend4 = new Friend("taka");

        System.out.println(Friend.numberOfFriends);

        Friend.displayFriends();

    }

}

static がついているフィールド変数やメソッドはそのクラスで共有します。

Friend.java
public class Friend {

    String name;
    static int numberOfFriends;

    public Friend(String name) {
        this.name = name;
        numberOfFriends++;
    }

    static void displayFriends() {
        System.out.println("You have " + numberOfFriends + " friends");
    }

}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0