今回は、
【モデリングについて】の復習b、c、d で作成した「Student」 「Teacher」 「School」 、
【カプセル化について】の復習a、b、c で作成した「Student2」「Teacher2」「School2」、
をコンパイルしてコンパイルがうまくいばプログラムを実行します。
【カプセル化について】の復習 の方は修飾子「private」でカプセル化したフィールドの値を変更しようとしているのでコンパイルできないか実行できないハズです。
- 「Student」「Teacher」「School」のコンパイルとプログラムの実行
- 「Student」「Teacher」「School」のソース
-
「Student」01 : public class Student {
02 : String name_ ; /* 名前 */
03 : int age_ ; /* 年齢 */
04 :
05 : public Student(String name, int age){
06 : name_ = name;
07 : age_ = age;
08 : }
09 :
10 : public void studentdate(){
11 : System.out.println(name_+ "("+age_+"歳)");
12 : }
13 : }
「Teacher」01 : public class Teacher {
02 : String name_ ; /* 名前 */
03 :
04 : public Teacher(String name){
05 : name_ = name;
06 : }
07 :
08 : public void studentdateCheck(Student s1,Student s2,Student s3){
09 : System.out.println(this.name_+"先生のクラスの生徒の名前と年齢");
10 : s1.studentdate();
11 : s2.studentdate();
12 : s3.studentdate();
13 : s1.age_ = 41;
14 : s1.studentdate();
15 : }
16 : }
「School」01 : public class School {
02 : public static void main(String[] args){
03 : Teacher teacher1 = new Teacher("野村");
04 : Student student1 = new Student("山崎", 40);
05 : Student student2 = new Student("田中", 20);
06 : Student student3 = new Student("岩隈", 27);
07 :
08 : teacher1.studentdateCheck(student1, student2 ,student3);
09 : }
10 : }
- コンパイル
- 「Student」「School」「Teacher」どれも問題なくコンパイルできました。
- 「School」の実行
- 以下のようになりました。
野村先生の生徒の名前と年齢山崎の年齢が40歳から41歳に変更できました。
山崎(40歳)
田中(20歳)
岩隈(27歳)
山崎(41歳)
- 「Student2」「Teacher2」「School2」のコンパイルとプログラムの実行
- 「Student2」「Teacher2」「School2」のソース
-
「Student2」01 : public class Student2 {
02 : private String name_ ; /* 名前 */
03 : private int age_ ; /* 年齢 */
04 :
05 : public Student2(String name, int age){
06 : name_ = name;
07 : age_ = age;
08 : }
09 :
10 : public void studentdate(){
11 : System.out.println(name_+ "("+age_+"歳)");
12 : }
13 : }
「Teacher2」01 : public class Teacher2 {
02 : private String name_ ; /* 名前 */
03 :
04 : public Teacher2(String name){
05 : name_ = name;
06 : }
07 :
08 : public void studentdateCheck(Student2 s1,Student2 s2,Student2 s3){
09 : System.out.println(this.name_+"先生のクラスの生徒の名前と年齢");
10 : s1.studentdate();
11 : s2.studentdate();
12 : s3.studentdate();
13 : s1.age_ = 41;
14 : s1.studentdate();
15 : }
16 : }
「School2」01 : public class School2 {
02 : public static void main(String[] args){
03 : Teacher2 teacher1 = new Teacher2("野村");
04 : Student2 student1 = new Student2("山崎", 40);
05 : Student2 student2 = new Student2("田中", 20);
06 : Student2 student3 = new Student2("岩隈", 27);
07 :
08 : teacher1.studentdateCheck(student1, student2 ,student3);
09 : }
10 : }
- コンパイル
- 「Student2」はコンパイルできましが、
「Teacher2」「School2」は以下のようなエラーが発生しました。
java:13: age_ は Student2 で private アクセスされます。予想通り、「private」でカプセル化したフィールドの値を変更しようとしているのでコンパイルできませんでした。
s1.age_= 41;