package overrideExercise;
//编写一个Person类,包括属性/private(name、age),构造器、方法say(返回自我介绍的字符串)
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String say() {
return "name=" + name + " age=" + age;
}
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;
}
}
package overrideExercise;
//编写一个Student类,继承Person类,增加id、score属性/private,以及构造器,定义say方法(返回自我介绍的信息)。
public class Student extends Person{
private int id;
private double score;
public Student(String name, int age, int id, double score) {
super(name, age);//这里会调用父类构造器
this.id = id;
this.score = score;
}
//say
@Override
public String say() { //这里体现super的一个好处,代码复用.
return super.say() + " id=" + id + " score=" + score;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
}
package overrideExercise;
public class Test {
public static void main(String[] args) {
//在main中,分别创建Person和Student对象,调用say方法输出自我介绍
Person jack = new Person("jack", 10);
System.out.println(jack.say());
Student smith = new Student("WTY", 20, 123456, 99.8);
System.out.println(smith.say());
}
}