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");
}
}