1. package overrideExercise;
    2. //编写一个Person类,包括属性/private(name、age),构造器、方法say(返回自我介绍的字符串)
    3. public class Person {
    4. private String name;
    5. private int age;
    6. public Person(String name, int age) {
    7. this.name = name;
    8. this.age = age;
    9. }
    10. public String say() {
    11. return "name=" + name + " age=" + age;
    12. }
    13. public String getName() {
    14. return name;
    15. }
    16. public void setName(String name) {
    17. this.name = name;
    18. }
    19. public int getAge() {
    20. return age;
    21. }
    22. public void setAge(int age) {
    23. this.age = age;
    24. }
    25. }
    1. package overrideExercise;
    2. //编写一个Student类,继承Person类,增加id、score属性/private,以及构造器,定义say方法(返回自我介绍的信息)。
    3. public class Student extends Person{
    4. private int id;
    5. private double score;
    6. public Student(String name, int age, int id, double score) {
    7. super(name, age);//这里会调用父类构造器
    8. this.id = id;
    9. this.score = score;
    10. }
    11. //say
    12. @Override
    13. public String say() { //这里体现super的一个好处,代码复用.
    14. return super.say() + " id=" + id + " score=" + score;
    15. }
    16. public int getId() {
    17. return id;
    18. }
    19. public void setId(int id) {
    20. this.id = id;
    21. }
    22. public double getScore() {
    23. return score;
    24. }
    25. public void setScore(double score) {
    26. this.score = score;
    27. }
    28. }
    1. package overrideExercise;
    2. public class Test {
    3. public static void main(String[] args) {
    4. //在main中,分别创建Person和Student对象,调用say方法输出自我介绍
    5. Person jack = new Person("jack", 10);
    6. System.out.println(jack.say());
    7. Student smith = new Student("WTY", 20, 123456, 99.8);
    8. System.out.println(smith.say());
    9. }
    10. }

    image.png