1.Java中常见的重写

重写toString()、equals()、hashcode()、compareTo()、compare()

接下来将从两方面分析

  • 为什么要重写这几个方法?
  • 怎么重写这几个方法?

toString()

public class Student {
    String name;
    int age;
    String address;
    public Student() {
    }
    public Student(String name, int age, String address) {
        this.name = name;
        this.age = age;
        this.address = address;
    }
    }
}
public class testForStudent {
    public static void main(String[] args) {
        Student st1 = new Student("嘉文四世",20,"德玛西亚");
        Student st2 = new Student("卡萨丁",50,"虚空");
        Student st3 = new Student("卡莎",18,"虚空");
        Student st4 = new Student("提莫",6,"扭曲丛林");
        Student st5 = new Student("寒冰",18,"弗雷尔卓德");
        Student st6 = new Student("寒冰",18,"弗雷尔卓德");

        System.out.println(st1);
    }
}

输出是:

indiv.zcg.day912.Student@1b6d3586

如果不重新toString()方法,toString方法默认输出的是对象的地址!像String、Interger这种类其实都已经将toString重写了

查阅代码可知

public String toString() {
    return this;
}

如果不重写toString,即Object类中的

public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

这就解释了为什么上面我们的输出是一个类全限类名@一个16进制数

那么如何重写?

public class Student {
    String name;
    int age;
    String address;
    public Student() {
    }
    public 
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值