Created
June 5, 2024 22:08
-
-
Save LeoAndo/b944668a139ce776b51d7e4cc5382b92 to your computer and use it in GitHub Desktop.
[Java] クラスフィールドとインスタンスフィールドの実験
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// クラスフィールドとインスタンスフィールドの実験目的なため、コンストラクタやアクセサメソッドなどは用意しない. | |
public class Student { | |
// クラスフィールド | |
private static String schoolName; | |
// インスタンスフィールド | |
private String name; | |
private int age; | |
public static void main(String[] args) { | |
System.out.println("==========Tanaka==========="); | |
final Student tanaka = new Student(); // インスタンス生成 | |
Student.schoolName = "ABC専門学校"; | |
tanaka.name = "Tanaka"; | |
tanaka.age = 20; | |
System.out.println("schoolName: " + Student.schoolName + " name: " + tanaka.name + " age: " + tanaka.age); | |
// クラス / インスタンスフィールドの値を更新 | |
Student.schoolName = "DEF専門学校"; | |
tanaka.name = "Tanaka Update!"; | |
tanaka.age = 30; | |
System.out.println("schoolName: " + Student.schoolName + " name: " + tanaka.name + " age: " + tanaka.age); | |
System.out.println("==========Yamada==========="); | |
final Student yamada = new Student(); // インスタンス生成 | |
// 別インスタンスを生成して、各フィールドの情報が取得できるか確認する | |
System.out.println("schoolName: " + Student.schoolName + " name: " + yamada.name + " age: " + yamada.age); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
クラスフィールド (staticが付いてるフィールド)として定義すると、異なるインスタンスでデータを共有できる
実行結果