Java方法重写

Java方法的重写

重写:需要有继承关系,子类重写父类的方法!

	1. 方法名必须相同
	2. 参数列表必须相同
	3. 修饰符:范围可以扩大但不能缩小:public>protected>default>private
	4. 抛出的异常:范围可以缩小,不能扩大; ClassNotFoundException --> Exception(大)

重写,子类的方法和父类必须一致,方法体不同!

为什么需要重写:

  1. 父类的功能,子类不一定需要,或不一定满足!

Alt + insert ; override;

代码

public class Person {

    public void eat(){
        System.out.println("P eat");
    }
}

public class Student extends Person{

    @Override
    public void eat() {
        super.eat();
    }
}


public class Application {
    public static void main(String[] args) {
        Student student = new Student();
        Person p1 = new Student();

        student.eat();
        p1.eat();
    }
}
posted @ 2021-11-02 16:34  石磬  阅读(133)  评论(0)    收藏  举报