方法的重写

方法的重写

概念:子类继承父类之后,就拥有了符合权限的父类的属性和方法,但是当父类的方法不符合子类的要求的时候,子类也可以重新的书写自己想要的方法。所以,方法的重写,即子类继承父类的方法后,由于父类的方法不满足子类的需求,子类重新书写该方法。

方法重写的条件

  1. 在子类中重写父类的方法。
  2. 返回值类型、方法名、参数列表必须和父类重写的方法一模一样。
  3. 访问修饰符不能被父类重写的方法更严格。
  4. 抛出的异常必须比父类的要小。

代码实现:

java 复制代码
//创建父类Person
class Person {
    public void eat(){
        System.out.println("吃食物");
    }
    public void sleep(){
        System.out.println("睡觉");
    }
}

//创建子类Student
class Student extends Person {
    public void study(){
        System.out.println("学习");
    }
@override
    public void eat(){
        System.out.println("我喜欢吃螺蛳粉。");
    }
}

public class Test {
    //这是一个main方法,是程序的入口:
    public static void main(String[] args) {
        //创建一个Student类的对象:
        Student student = new Student();
        student.eat();
    }
}

运行结果:

方法重写VS方法重载

名称 发生范围 方法名 形参列表 返回类型 修饰符
重载(Overload) 本类 必须一样 类型,个数或者顺序至少有一个不同 无需求 无需求
重写(Override) 父子类 必须一样 相同 子类重写的方法,返回的类型和父类返回的类型一致,或者是其子类 子类方法不能缩小父类方法的访问范围
相关推荐
有一个好名字1 分钟前
Spring AI ——Java开发者的AI集成神器
java·人工智能·spring
i***68323 分钟前
Spring Boot--@PathVariable、@RequestParam、@RequestBody
java·spring boot·后端
p***95008 分钟前
Plugin ‘org.springframework.bootspring-boot-maven-plugin‘ not found的解决方法
java·maven
h***066518 分钟前
Spring Boot 集成 Kettle
java·spring boot·后端
旷野说1 小时前
如何用 Redpanda + 本地事务,实现“发消息 + 写 DB” 的强一致性!
java·数据库·kafka
unclecss1 小时前
从 0 到 1 落地 SSE:Spring Boot 3 实战 Server-Sent Events 推送全链路
java·spring boot·后端·http·sse
e***95641 小时前
springboot-自定义注解
java·spring boot·spring
stormsha1 小时前
Java 设计模式探秘饿汉式与懒汉式单例模式的深度解析
java·单例模式·设计模式·java-ee
稚辉君.MCA_P8_Java1 小时前
DeepSeek Java 多线程打印的19种实现方法
java·linux·jvm·后端·架构
白露与泡影1 小时前
spring Security 认证流程闭环与调用链路详解
java·后端·spring