代码示例
| public class OverrideExercise { |
| public static void main(String[] args) { |
| Person jack = new Person("jack", 18); |
| System.out.println(jack.say()); |
| Student smith = new Student("smith", 18, 1, 99); |
| System.out.println(smith.say()); |
| } |
| } |
| class Person { |
| private String name; |
| private int age; |
| public Person(String name, int age) { |
| this.name = name; |
| this.age = age; |
| } |
| public String say() { |
| return "name=" + name + ",age=" + age; |
| } |
| } |
| class Student extends Person { |
| private int id; |
| private double score; |
| public Student(String name, int age, int id, double score) { |
| super(name, age); |
| this.id = id; |
| this.score = score; |
| } |
| @Override |
| public String say() { |
| return super.say() + ",id=" + id + ",score=" + score; |
| } |
| } |
注意事项
- 方法重写override存在于父类与子类中
- 方法名保持一致
- 方法形参列表保持一致
- 子类方法的返回值应与父类方法返回值一致或者为其子类
- 父类返回值若为Object,则子类返回值可以为Object或者其他Object子类
- 子类方法的修饰符应与父类方法修饰符一致或者比其更大
- 父类方法修饰符若为protected,则子类方法修饰符可以为protected或者public
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)