首页 > 代码库 > 第十四章----面向对象equals和toString的重写

第十四章----面向对象equals和toString的重写

权限修饰符

技术分享

成员变量初始化

技术分享

1、toString方法的重写

public class Test extends Object {
    private int id;
    private String name;
    
    public Test(int id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public String toString() {
        return "Test [id=" + id + ", name=" + name + "]";
    }
    

    
}

2、equals方法的重写

举例:一个自定义类ball如下

 
public class Student {
    private String name;
    private int weight;
    
    public Student(String name,int weight){
      this.name = name;
      this.weight = weight;
    }
}
 

我们可以这样重写equals方法:

 
 public boolean equals(Object obj){
        if(obj == null){
            return false;
        }else{
            if(obj instanceof Student){
               Student stu = (Student)obj;
                if(this.name == stu.name&&this.weight==stu.weight){
                    return true;
                }
            }
            
        }
        return false;
    } 

第十四章----面向对象equals和toString的重写