JAVA方法的重写

方法的重写(override/overwrite)

定义:

在子类中可以根据需要,对从父类中继承来的方法进行改造,也称为方法的重置,覆盖。在程序执行时,子类的方法将覆盖父类的方法

要求:

  1.子类重写的方法必须与父类被重写的方法具有相同的方法名称,参数列表

  2.子类重写的方法返回值类型不能大于父类中被重写的方法的返回值类型

  3.子类重写的方法使用的访问权限不能小于父类被重写的方法的访问权限

  子类不能重写父类中声明为private权限的方法

  4.子类方法抛出的异常不能大于父类被重写方法的异常

注意:

子类与父类中同名同参数的方法必须同时声明为非static的(即为重写,或者同时声明为static的(不是重写),因为static方法属于类的,子类无法覆盖父类的方法。

新建一个Person类

public class Person {
    String name;
    int age;
    public Person(){

    }
    public Person(String name,int age){
        this.name = name;
        this.age = age;
    }
    public void eat(){
        System.out.println("人吃饭");
    }
    public void walk(int distance){
        System.out.println("人走路,走的距离是"+distance+"公里");
    }
}

再建一个子类Student,继承Person类

public class Student extends Person {

    String major;
    public Student(){

    }
    public Student(String major){
        this.major = major;
    }
    public void study(){
        System.out.println("学生学习,专业是"+major);
    }
    //该方法对父类方法进行了重写
    public void eat(){
        System.out.println("学生吃饭");
    }

}

接下来建一个PersonTest 验证一下子类重写父类方法后的的调用

public class PersonTest {
    /**
     * 1.重写,子类继承父类后,可以对父类同名同参数的方法进行重写
     * 2.应用:重写以后,当通过子类的对象调用被重写的方法时,实际执行的是子类重写以后的方法
     * @param args
     */
    public static void main(String[] args) {

        Student student =new Student("计算机科学与技术");
        //通过子类对象调用父类的方法
        student.walk(5);
        //通过子类对象调用子类中的方法
        student.study();
        //通过子类对象调用后,执行的是子类中重写父类的方法
        student.eat();
        //父类对象调用父类方法,依然执行的是父类的代码方法
        Person person =new Person();
        person.eat();
    }
}

 

posted @ 2021-03-11 21:10  懒惰的咸鱼  阅读(194)  评论(0编辑  收藏  举报