2020 |
07,14 |
«static_1»
staticを使ったやつ
class User {
private String name;
private static int count = 0;
public User(String name) {
this.name = name;
//インスタンス化するためにこちらのcountを1ずつふやしていく
//staticのフィールドに対してアクセスるにはクラス名を使えばいいので
//『User.count++;』のようにかいてあげるとよい
User.count++;
}
public static void getInfo() { // クラスメソッド
System.out.println("# of instances: " + User.count);
}
}
//mai()は特殊なメソッドではあるのですがJavaの仮想マシンがMyAppの
//インスタンスを作らずにいきなり実行できるようにstaticメソッドになっていると
//理解しておくといいでしょう。
public class MyApp {
public static void main(String[] args) {
User.getInfo(); // 0
User tom = new User("tom");
User.getInfo(); // 1
User bob = new User("bob");
User.getInfo(); // 2
}
}
PR
Post your Comment