方法重写/覆盖

方法重写/覆盖

基本介绍

简单来说:方法覆盖(重写)就是子类有一个方法,和父类的某个方法的名称、返回类型、参数一样,那么我们就说子类的这个方法覆盖了父类的那个方法。

注意事项和使用细节

方法重写也叫方法覆盖,需要满足下面的条件

  1. 子类的方法的形参列表,方法名称,要和父类的方法参数,方法名称完全一样。
  2. 子类方法的返回类型和父类方法返回类型一样,或者是父类返回类型的子类。 比如,父类的返回类型是Object,子类的返回类型就是String
  3. 子类方法不能缩小父类方法的访问权限

运行示例:

public class OverrideExercise {
    public static void main(String[] args) {
        Person person = new Person("ming", 23);
        System.out.println(person.Say());
        Student student = new Student("hong", 16, 1, 120);
        System.out.println(student.Say());

    }
}

class Person {
    private String name;
    private int age;

    public Person() {

    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String Say() {
        return "my name is " + name + " i'm " + age + " years old" + "\n";
    }
}

class Student extends Person {
    private int id;
    private int score;

    public Student() {

    }
    public Student(String name, int age, int id, int score) {
        super(name, age);
        this.id = id;
        this.score = score;
    }
    public String Say() {  //这里体现super的好处,代码复用
        return super.Say() + "my id is " + id + " my score is " + score + "\n";
    }

}

运行示例:
my name is ming i'm 23 years old

my name is hong i'm 16 years old
my id is 1 my score is 120

posted @ 2021-03-14 22:33  Irisx33  阅读(140)  评论(0)    收藏  举报