java当中的重写


一.什么是重写

在子类中创建了一个与父类中名称相同、返回值类型相同、参数列表的方法相同,只是方法体中的实现不同,以实现不同于父类的功能,这种方式被称为方法重写(override),又称为方法覆盖、方法复写。

二.重写的要求

1.重写是只能在继承当中用到的
2.要求父类与子类的方法名,形参列表相同
3.子类重写方法的权限修饰符要不小于父类的权限修饰符

class Person{
    public void eat(){
        System.out.println("吃饭!");
    }
}
class Student extends Person{
    protected void eat(){
        System.out.println("吃好的!");
    }
}
public class Test {
    public static void main(String[] args) {
       Student stu = new Student();
       stu.eat();
    }
}

在这里插入图片描述
这里我重写父类方法eat()的时候,我将子类的修饰限定符调的比父类低了,然后造成了无法覆盖问题
4.子类不能重写父类中private的方法

lass Person{
    public void walk(){
        System.out.println("走路");
        show();
    }
    private void show(){
        System.out.println("展示父类");
    }
}
class Student extends Person{

    public void show(){
        System.out.println("展示子类");
    }
}
public class Test {
    public static void main(String[] args){
        Student stu = new Student();
        stu.walk();
    }
}

在这里插入图片描述

这里被重写的show()方法权限是private的,所以这里重写的show()方法是不管用的,那就代表着父类的show()方法没有被重写,因此在用子类对象调用重写的方法时,还是调用的父类的show()方法。

5.重写时子类的返回值类型要么与父类方法的返回值类型相同,要么是父类方法的返回值类型的子类

class Person{
    public Person walk(){
        System.out.println("走路");
        Person p = new Person();
        return p;
    }

}
class Student extends Person{
    public Student walk(){
        System.out.println("跑步");
        Student student = new Student();
        return student;
    }

}
public class Test {
    public static void main(String[] args){
        Student stu = new Student();
        stu.walk();
    }
}

在这里插入图片描述
这里就是重写的返回值类型时被重写返回值类型的子类,其他都相同,也可以完成重写
6.被重写的一定要是非静态的方法,因为静态的方法只与类名有关,与对象无关,而重写必须要用子类的对象来调用那个重写的方法,所以静态的方法不可以重写。
7.重写方法中被抛出的异常的范围要大于被重写方法中抛出的异常
8.声明为final的方法不能重写

三.重写的作用

  1. 重写是为了增强类的重用性和复用性,扩展性。

  2. 重写是对类中方法的扩充,因为继承用的是父类的东西,而重写是用的自己的东西。