主题:对象的比较和字符串表示
描述:
- 这个任务涉及到
equals()
方法的重写,以实现自定义对象比较逻辑。 toString()
方法也被重写,用于提供对象的字符串表示形式。- 通过创建
Account8_1_1
类的对象,并调用equals()
和toString()
方法,可以测试这些重写方法的功能。
在Account类中重写equals()方法和toString()方法,并创建对象测试这两个方法的使用。
package shiyan8;
public class Account8_1_1 {
// 定义账户的属性:账号id和余额
private String id;
private double balance;
public Account8_1_1(String id, double balance) {
this.id = id;
this.balance = balance;
}
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Account8_1_1 account = (Account8_1_1) obj;
return id != null ? id.equals(account.id) : account.id == null;
}
public String toString() {
return "{" +
"账号='" + id + '\'' +
", 余额=" + balance +
'}';
}
public static void main(String[] args) {
Account8_1_1 account1 = new Account8_1_1("001", 1000.0);
Account8_1_1 account2 = new Account8_1_1("001", 1000.0);
System.out.println(account1);
System.out.println(account1.equals(account2) ? "两个账户相等" : "两个账户不相等");
}
}