image.png

    1. package com.atguigu.exercise4;
    2. public class MyDate {
    3. private int day;
    4. private int month;
    5. private int year;
    6. public MyDate(int day,int month,int year){
    7. this.day = day;
    8. this.month = month;
    9. this.year = year;
    10. }
    11. public int getDay() {
    12. return day;
    13. }
    14. public void setDay(int day) {
    15. this.day = day;
    16. }
    17. public int getMonth() {
    18. return month;
    19. }
    20. public void setMonth(int month) {
    21. this.month = month;
    22. }
    23. public int getYear() {
    24. return year;
    25. }
    26. public void setYear(int year) {
    27. this.year = year;
    28. }
    29. @Override
    30. public boolean equals(Object obj) {
    31. if(this == obj){//先比较地址
    32. return true;
    33. }
    34. if(obj instanceof MyDate){//判断是否为MyDate
    35. MyDate myDate= (MyDate)obj;
    36. return this.day == myDate.day && this.month == myDate.month &&
    37. this.year == myDate.year; //比较每个属性
    38. }
    39. return false;
    40. }
    41. // @Override
    42. // public boolean equals(Object obj) {
    43. // if (this == obj)
    44. // return true;
    45. // if (obj == null)
    46. // return false;
    47. // if (getClass() != obj.getClass())
    48. // return false;
    49. // MyDate other = (MyDate) obj;
    50. // if (day != other.day)
    51. // return false;
    52. // if (month != other.month)
    53. // return false;
    54. // if (year != other.year)
    55. // return false;
    56. // return true;
    57. // }
    58. }

    1. package com.atguigu.exercise4;
    2. public class MyDateTest {
    3. public static void main(String[] args) {
    4. MyDate m1 = new MyDate(14,3,1976);
    5. MyDate m2 = new MyDate(14,3,1976);
    6. if(m1 == m2){
    7. System.out.println("m1==m2");
    8. }else {
    9. System.out.println("m1 != m2");
    10. }
    11. if(m1.equals(m2)){
    12. System.out.println("m1 is equals to m2");
    13. }else{
    14. System.out.println("m1 is not equals to m2");
    15. }
    16. }
    17. }