Person.java
public class Person {
String name;
char sex;
int age;
public Person(String name, char sex, int age) {
this.name = name;
this.sex = sex;
this.age = age;
}构造函数,设置父类person对象信息
String show() {
return "姓名:" + name + ", 性别:"+ sex + ", 年龄:" + age;
}//输出父类person对象信息
}
Student.java
public class Student extends Person{
int id;
public Student(String name, char sex, int age, int id) {
super(name, sex, age); //调用父类构造函数
this.id = id;
}构造函数,设置子类student对象信息
String show() {
return super.show() + ", 学号:" + id;
}//输出子类student对象信息
}
Teacher.java
public class Teacher extends Person{
String course;
public Teacher(String name, char sex, int age, String course) {
super(name, sex, age);//调用父类构造函数
this.course = course;
}构造函数,设置子类teacher对象信息
String show() {
return super.show() + ", 所属课程:" + course;
}//输出子类teacher对象信息
}
PersonApp.java
public class PersonApp {
public static void main(String[] args) {
Person person = new Person("person", '男', 20);
System.out.println(person.show());//设置父类person信息并输出
Student student = new Student("student", '女', 18, 16010101);
System.out.println(student.show());//设置子类student信息并输出
Teacher teacher = new Teacher("teacher", '女', 22, "English");
System.out.println(teacher.show());//设置子类teacher信息并输出
}
}