Java基础之Object 的方法重写与toString的方法重写

Object 类的介绍
java.lang.Object 类

1.Object 类是所以Java类的父类
2.如果在类的声明中未使用extends关键字指定其父类,则默认父类为java.lang.Object类
3.Object 类中的功能(属性、方法)就具有通用性
没有属性,
finalize() 垃圾回收方法
方法:equals() / toString()/getCalss()/hashCode()/ clone()/finalize(
wait()/notify()/notifyAll()
4.Object 类有一个空参构造器
NO 方法名称 类型 描述
1 public Object() 构造 构造器
2 public boolean equals() 方法 对象比较
3 public int hashCode() 方法 取得Hash码
4 public String toString() 方法 对象打印时调用
==操作符与equals方法 的区别
 
==操作符与equals方法
==,运算符
1.可以使用在基本数据类型变量和引用数据类型变量中
2.如果比较的时基本数据类型的变量,比较两个变量保存的数据怒是否相等(不一定类型相同)
3. 如果比较的是引用数据类型,比较的就是两个对象的地址值是否相同
equals方法
1.是一个方法,而非运算符
2.只适用于引用数据类型
3.Object 类中equals 的定义
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
public boolean equals(Object obj) {
       return (this == obj);
   }
   Object 类中定义的equals方法和==符号相同的
   String 类中equals的定义
   public boolean equals(Object anObject) {
       if (this == anObject) {
           return true;
       }
       if (anObject instanceof String) {
           String anotherString = (String)anObject;
           int n = value.length;
           if (n == anotherString.value.length) {
               char v1[] = value;
               char v2[] = anotherString.value;
               int i = 0;
               while (n-- != 0) {
                   if (v1[i] != v2[i])
                       return false;
                   i++;
               }
               return true;
           }
       }
       return false;
   }

 

像String、Date、File、包装类等都重写了Object类中的equals()方法,重写以后
比较的不是两个引用的地址是否相同,而是比较两个对象内容是否相同
通常情况下,自定义类如果使用equals()的话,通常也是比较两个对象的“实体
内容”是否相同,那么就需要对equals()方法进行重写
创建类并重写equals方法
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
32
33
34
35
36
37
38
39
40
41
42
43
44
package com.chenxi.test;
 
public class Customer {
    private String name;
    private int age;
    public Customer (){}
    public Customer(String name,int age){
        this.age = age;
        this.name = name;
    }
 
    public int getAge() {
        return age;
    }
 
    public void setAge(int age) {
        this.age = age;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String getName() {
        return name;
    }
//重写equals方法
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj instanceof Customer){
            Customer cust= (Customer)obj;
            if (this.age==cust.age && this.name.equals(cust.name)){
                return true;
            }else {
                return false;
            }
 
        }
        return  false;
    }
 
}

  idea 自动生成equals 方法 快捷键Alt+Insert  选择equals() and hashCode() 选项进行自动代码生成

      点击 Code 菜单中的 Generate…选项 ,也可使用快捷键 alt+insert ,点击 toString() 选项,选择需要包含的成员变量并确定。

自动生成的

1
2
3
4
5
6
7
8
@Override
   public boolean equals(Object o) {
       if (this == o) return true;
       if (!(o instanceof Customer)) return false;
       Customer customer = (Customer) o;
       return getAge() == customer.getAge() &&
               Objects.equals(getName(), customer.getName());
   
对称性:如果x.equals(y)返回是“true”,那么y.equals(x)也应该返回是“true”。
自反性:x.equals(x)必须返回是“true”。
传递性:如果x.equals(y)返回是“true”,而且y.equals(z)返回是“true”,
那么z.equals(x)也应该返回是“true”。
一致性:如果x.equals(y)返回是“true”,只要x和y内容一直不变,不管你
重复x.equals(y)多少次,返回都是“true”。
任何情况下,x.equals(null),永远返回是“false”;
x.equals(和x不同类型的对象)永远返回是“false”
 toString方法
object类里toString的使用
1.当调用一个对象的引用时,实际上就是调用当前对象toString的引用
2.Object String toString()的定义
1
2
3
4
Object类中toString()的定义
 public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }
3.像String、Date、Flies、包装类等都重写了Object类中的tostring方法使得在调用对象的toString(),返回“实体内容”信息

4.自定义类也可以重写toString()方法,当调用此方法时返回对象的实体内容
测试类
1
2
3
4
5
6
7
8
9
10
11
12
13
public class ToStringTest {
    public static void main(String[] args) {
 
 
        Customer c1 = new Customer();
        Customer c2 = new Customer();
        System.out.println(c1.toString());
        System.out.println(c1);
        String str1 = new String("MM");//重写过toString
        System.out.println(str1);
    }
 
}

  customer 类

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
package com.chenxi.test;
 
public class Customer {
    private String name;
    private int age;
    public Customer (){}
    public Customer(String name,int age){
        this.age = age;
        this.name = name;
    }
 
    public int getAge() {
        return age;
    }
 
    public void setAge(int age) {
        this.age = age;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String getName() {
        return name;
    }
}

  测试结果

1
2
3
com.chenxi.test.Customer@1540e19d
com.chenxi.test.Customer@1540e19d
MM

  重写customer的toSting方法

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
32
33
package com.chenxi.test;
 
public class Customer {
    private String name;
    private int age;
    public Customer (){}
    public Customer(String name,int age){
        this.age = age;
        this.name = name;
    }
 
    public int getAge() {
        return age;
    }
 
    public void setAge(int age) {
        this.age = age;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String getName() {
        return name;
    }
    @Override
    public String toString() {
        return "Customer{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

  测试结果

1
2
3
Customer{name='null', age=0}
Customer{name='null', age=0}
MM

  示例

父类

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
32
33
34
35
36
package com.chenxi.exer2;
 
public class GeometricObject {
    protected String color;
    //体积
    protected double weighgt;
    protected GeometricObject(){
        this.color="white";
        this.weighgt=1.0;
    }
//    protected GeometricObject(String color,double weighgt){
//        this.color = color;
//        this.weighgt= weighgt;
//    }
 
    public GeometricObject(String color, double weighgt) {
        this.color = color;
        this.weighgt = weighgt;
    }
 
    public String getColor() {
        return color;
    }
 
    public void setColor(String color) {
        this.color = color;
    }
 
    public double getWeighgt() {
        return weighgt;
    }
 
    public void setWeighgt(double weighgt) {
        this.weighgt = weighgt;
    }
}

  子类

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
32
33
34
35
36
37
38
39
40
41
42
package com.chenxi.exer2;
 
public class Circle extends GeometricObject {
    private double radius;//半径
    public Circle(){
        radius = 1.0;
 
    }
    public  Circle(double radius){
        this.radius = radius;
    }
 
    public Circle(String color, double weighgt, double radius) {
        super(color, weighgt);
        this.radius = radius;
    }
 
    public double getRadius() {
        return radius;
    }
 
    public void setRadius(double radius) {
        this.radius = radius;
    }
    public double findArea(){
 
        return radius*radius*3.14;
    }
    public boolean equals(Object obj){
        if (this == obj) return true;
        if (!(obj instanceof Circle)) return false;
        Circle c1 = (Circle)obj;
        return c1.getRadius()==getRadius()&&
                c1.getWeighgt()==getWeighgt()&&
                c1.getColor()==getColor()&&
                c1.findArea()==findArea();
    }
 
    public String toString(){
        return "radius是["+radius+"]";
    }
}

  测试类

1
2
3
4
5
6
7
8
9
10
11
12
package com.chenxi.exer2;
 
public class GeometricObjectTest {
    public static void main(String[] args){
        Circle c1 = new Circle("color",8.0,3.0);
        System.out.println(c1.getRadius());
        System.out.println(c1.findArea());
        Circle c2 = new Circle("color",8.0,3.0);
        System.out.println(c2.equals(c1));
 
    }
}

  测试结果

1
2
3
3.0
28.26
true
 
posted @   烟雨楼台,行云流水  阅读(543)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏
点击右上角即可分享
微信分享提示