オブジェクト指向(継承)

Java

お題

以下はStudentクラスとTeacherクラスとアプリケーションクラスSchoolAppクラスのソースコードである。

public class SchoolApp{
	public static void main(String[] args){
		Teacher t = new Teacher("山田",35,"数学");
		t.greeting();
		t.teach();
		Student s = new Student("鈴木",15,8);
		s.greeting();
		s.showNumber();
	}
}

class Teacher{
	String name;
	int age;
	String subject;

	Teacher(String name,int age,String subject){
		this.name=name;
		this.age=age;
		this.subject=subject;
	}

	void greeting(){
		System.out.printf("%s(%d)です。こんにちは%n",this.name,this.age);
	}

	void teach(){
		System.out.printf("%sの授業を行います%n",this.subject);
	}
}

class Student{
	String name;
	int age;
	int number;

	Student(String name,int age,int number){
		this.name=name;
		this.age=age;
		this.number=number;
	}

	void greeting(){
		System.out.printf("%s(%d)です。こんにちは%n",this.name,this.age);
	}

	void showNumber(){
		System.out.printf("出席番号は%dです%n",this.number);
	}
}

親クラスPersonの作成

TeacherクラスとStudentクラスの共通部分から親クラスPersonを作成し、TeacherクラスとStudentクラスをPersonの子クラスとして設計し直すこと。
(上記ソースのmainメソッドには変更を加えないこと)

[実行例]

山田(35)です。こんにちは
数学の授業を行います
鈴木(15)です。こんにちは
出席番号は8です

解答例


public class Main{
	public static void main(String[] args){
		Teacher t = new Teacher("山田",35,"数学");
		t.greeting();
		t.teach();
		Student s = new Student("鈴木",15,8);
		s.greeting();
		s.showNumber();
	}
}

class Person{
	String name;
	int age;

	Person(String name,int age){
		this.name=name;
		this.age=age;
	}
	void greeting(){
		System.out.printf("%s(%d)です。こんにちは%n",this.name,this.age);
	}
}

class Teacher extends Person{
	String subject;

	Teacher(String name,int age,String subject){
		super(name,age);
		this.subject=subject;
	}

	void teach(){
		System.out.printf("%sの授業を行います%n",this.subject);
	}
}

class Student extends Person{
	int number;

	Student(String name,int age,int number){
		super(name,age);
		this.number=number;
	}

	void showNumber(){
		System.out.printf("出席番号は%dです%n",this.number);
	}
}

Java
スポンサーリンク
シェアする
mjpurinをフォローする

コメント

タイトルとURLをコピーしました