例子一
package com.klvchen.exer2;
public class OrderTest {
public static void main(String[] args) {
Order order1 = new Order(1001, "AA");
Order order2 = new Order(1001, "BB");
System.out.println(order1.equals(order2)); //false
Order order3 = new Order(1001, "BB");
System.out.println(order2.equals(order3)); //true
String s1 = "BB";
String s2 = "BB";
System.out.println(s1 == s2); //true
}
}
class Order{
private int orderId;
private String orderName;
public int getOrderId() {
return orderId;
}
public void setOrderId(int orderId) {
this.orderId = orderId;
}
public String getOrderName() {
return orderName;
}
public void setOrderName(String orderName) {
this.orderName = orderName;
}
public Order(int orderId, String orderName) {
super();
this.orderId = orderId;
this.orderName = orderName;
}
@Override
public boolean equals(Object obj) {
if(this == obj) {
return true;
}
if(obj instanceof Order) {
Order order = (Order)obj;
return this.orderId == order.orderId &&
this.orderName.equals(order.orderName);
}
return false;
}
}
运行结果
例子二
请根据以下代码自行定义能满足需要的 MyDate 类,在MyDate类中覆盖equals方法,使其判断当两个MyDate类型对象的年月日都相同时,结果为true,否则为false。
MyDateTest.java
package com.klvchen.exer2;
public class MyDateTest {
public static void main(String[] args) {
MyDate m1 = new MyDate(14, 3, 1976);
MyDate m2 = new MyDate(14, 3, 1976);
if(m1 == m2) {
System.out.println("m1 == m2");
}else {
System.out.println("m1 != m2"); //m1 != m2
}
if(m1.equals(m2)) {
System.out.println("m1 is equal to m2"); //m1 is equal to m2
} else {
System.out.println("m1 is not equal to m2");
}
}
}
class MyDate{
private int day;
private int month;
private int year;
public MyDate(int day, int month, int year) {
super();
this.day = day;
this.month = month;
this.year = year;
}
public int getDay() {
return day;
}
public void setDay(int day) {
this.day = day;
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
this.month = month;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
MyDate other = (MyDate) obj;
if (day != other.day)
return false;
if (month != other.month)
return false;
if (year != other.year)
return false;
return true;
}
}