Java Object类练习 打印类的hashCode()值;打印类的class对象值;调用equals()方法比较两个对象;重写Object的equals()方法,比较类对象的属性值;重写Object的toString()方法,打印对象名。
时间: 2023-06-07 18:10:45 浏览: 119
好的,我明白了你的要求。关于你的问题,我可以给你一份示例代码,供你参考:
```java
public class ObjectDemo {
private String name;
private int age;
public ObjectDemo(String name, int age) {
this.name = name;
this.age = age;
}
public static void main(String[] args) {
ObjectDemo demo = new ObjectDemo("Tom", 25);
// 打印类的hashCode()值
System.out.println("HashCode of ObjectDemo: " + demo.hashCode());
// 打印类的class对象值
System.out.println("Class object of ObjectDemo: " + demo.getClass());
// 调用equals()方法比较两个对象
ObjectDemo demo1 = new ObjectDemo("Tom", 25);
ObjectDemo demo2 = new ObjectDemo("Tom", 26);
System.out.println("demo1 equals demo: " + demo1.equals(demo));
System.out.println("demo2 equals demo: " + demo2.equals(demo));
// 重写Object的equals()方法,比较类对象的属性值
System.out.println("demo1 content equals demo: " + demo1.contentEquals(demo));
// 重写Object的toString()方法,打印对象名
System.out.println("toString of demo: " + demo.toString());
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
ObjectDemo demo = (ObjectDemo) obj;
return age == demo.age && Objects.equals(name, demo.name);
}
public boolean contentEquals(ObjectDemo demo) {
return age == demo.age && Objects.equals(name, demo.name);
}
@Override
public String toString() {
return "ObjectDemo{" +
"name='" + name + '\'' +
'}';
}
}
```
希望能够帮到你,如果还有其他问题可以继续向我提问。
阅读全文