随笔 - 79,  文章 - 0,  评论 - 1,  阅读 - 45505

方法覆盖示例:

复制代码
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 + "日";
    }
    
}
复制代码

 

posted on   homle  阅读(204)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示