面向对象特性编程(继承和多态)
设计一个Student类和Teacher类,它们都继承Person类(参考下图),Student类中加入score(成绩)属性,Teacher类中加入salary(工资)属性,同时添加printInfo()方法,用来输出当前对象信息。
perso类
package Girl.Test3.E1;
public class Person {
private String name;
private int age;
private char sex;
private String add;
private String dept;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public Person(String name, int age, char sex, String add, String dept) {
this.name = name;
this.age = age;
this.sex = sex;
this.add = add;
this.dept = dept;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public char getSex() {
return sex;
}
public void setSex(char sex) {
this.sex = sex;
}
public String getAdd() {
return add;
}
public void setAdd(String add) {
this.add = add;
}
public String getDept() {
return dept;
}
public void setDept(String dept) {
this.dept = dept;
}
public String getInfo() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", sex=" + sex +
", add='" + add + '\'' +
", dept='" + dept + '\'' +
'}';
}
public void print() {
System.out.println(getInfo());
}
}
Student类
package Girl.Test3.E1;
public class Student extends Person {
private double score;
public Student(String name, int age, char sex, String add, String dept, double score) {
super(name, age, sex, add, dept);
this.score = score;
}
public String printInfo() {
return "Student{" +
"name='" + super.getName() + '\'' +
", age=" + super.getAge() +
", sex=" + super.getSex() +
", add='" + super.getAdd() + '\'' +
", dept='" + super.getDept() + '\'' +
", score='" + score + '\'' +
'}';
}
}
Teacher类
package Girl.Test3.E1;
public class Teacher extends Person {
private double salary;
public Teacher(String name, int age, char sex, String add, String dept, double salary) {
super(name, age, sex, add, dept);
this.salary = salary;
}
public String printInfo() {
return "Teacher{" +
"name='" + super.getName() + '\'' +
", age=" + super.getAge() +
", sex=" + super.getSex() +
", add='" + super.getAdd() + '\'' +
", dept='" + super.getDept() + '\'' +
", score='" + salary + '\'' +
'}';
}
}
Main类
package Girl.Test3.E1;
public class Main {
public static void main(String[] args) {
Student s1 = new Student("aa",12,'n',"地址","软件工程",98);
System.out.println(s1.printInfo());
Teacher t1 = new Teacher("aa",12,'n',"地址","软件工程",3000);
System.out.println(t1.printInfo());
}
}