方法覆盖示例:
public class OverrideTest01{ public static void main(String[] args){ //ChinaPeople cp = new ChinaPeople("张三"); //错误: 子类无法继承父类的构造方法; ChinaPeople cp = new ChinaPeople(); cp.setName("张三"); cp.speak(); AmericPeople ap = new AmericPeople(); ap.setName("tom"); ap.speak(); } } class People{ String name; //实例属性 public People(){ //构造方法 } public People(String name){ this.name = name; } //setter and getter public void setName(String name){ this.name = name; } public String getName(){ return this.name; } public void speak(){ System.out.println(name + " ....."); } } class ChinaPeople extends People{ public void speak(){ //重写父类的speak方法 System.out.println(this.getName() + "正在说汉语。"); } } class AmericPeople extends People{ public void speak(){ System.out.println(this.getName() + " is speaking."); } }
重写Object类中的toString()方法:
public class OverrideTest02{ public static void main(String[] args){ MyDate md = new MyDate(); System.out.println(md.toString()); //MyDate@512ddf17,默认输出对象在堆中的内存地址 System.out.println(md); //MyDate@512ddf17,对象后不带toString()输出结果一样,默认输出对象在堆中的内存地址 MyDate md1 = new MyDate(); //重写toString()方法后,“对象.toString()” 可以输出符合要求的年月日格式; System.out.println(md1.toString()); System.out.println(md1); } } class MyDate{ //MyDate类默认继承Object类,所以会默认继承Object类的toString()方法 private int year; private int month; private int day; public MyDate(){ this(1970,1,1); } public MyDate(int year, int month, int day){ this.year = year; this.month = month; this.day = day; } public void setYear(int year){ this.year = year; } public int getYear(){ return year; } public void setMonth(int month){ this.month = month; } public int getMonth(){ return month; } public void setDay(int day){ this.day = day; } public int getDay(){ return day; } public String toString(){ //重写Object类中的toString方法 return year + "年" + month + "月" + day + "日"; } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)