Java中的toString重写和equals重写
- equals默认是调用boject的方法;但子类和父类的哈希对象地址不可能一致;则需要对方法进行重写
- toString默认的调用object的方法;输出16进制的哈希对象地址值;这里通过重写;使其格式化输出
package com.msb02;
public class Person {
String name;
int age;
double hight;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getHight() {
return hight;
}
public void setHight(double hight) {
this.hight = hight;
}
public Person() {
}
public Person(String name, int age, double hight) {
this.name = name;
this.age = age;
this.hight = hight;
}
/*
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", hight=" + hight +
'}';
}*///这里的类型是object不是person;所以将object转为person
public boolean equals(Object obj) {
//这里是将obj转为Person类型;将父类向下转换成子类;调用子类特有属性;这里父类的对象属性obj;子类的person
Person other=(Person)obj;
if(this.getAge()==other.getAge()&&this.getName()==other.getName()&&this.getHight()==other.getHight()){
return true;
}
return false;
}
}
package com.msb02;
public class Test {
public static void main(String[] args) {
Person person = new Person("丽丽",24,165.3);
Person per =new Person("丽丽",24,165.3);
System.out.println(person.equals(per));//这个时equals比较两个值person大小
}
}