/*

 *   ==操作符与equals方法的区别:

 *   1: ==

 *   1.1 ==:引用类型比较引用(是否指向同一个对象);

 *   1.2 用"=" 进行比较时,符号两边的数据类型必须可兼容,否则编译出错

 *  

 *   2:equal

 *   2.1: equal

 */

public class Lesson21 {

    public static void main(String[] args) {

        Person person1 = new Person("李四", 30);

        Person person2 = new Person("张三", 30);

        //两个对象 肯定是不一样的。

        System.out.println(person1 == person2);

        //如果不重写,可能会导致不同

        //通过重写这个方法,会让两个对象一样, 比如两个人的年龄相同,就相同

        System.out.println(person1.equals(person2));

        System.out.println("----------------------");

        String str1= new String("1234");

        String str2= new String("1234");

        System.out.println(str1==str2);  //false

        System.out.println(str1.equals(str2)); //true  //因为它String类里面重写了Equal方法

        System.out.println("----------------------");

        String str3="12345";

        String str4="12345";

       

        System.out.println(str3==str4);  //true

        System.out.println(str3.equals(str4)); //true  //因为它String类里面重写了Equal方法

        System.out.println("----------------------");

       

        //传入相同的年月日

        MyDate mydate1 =new MyDate(2017,9,12);

        MyDate mydate2 =new MyDate(2017,9,12);

       

        System.out.println(mydate1==mydate2);  //true

        System.out.println(mydate1.equals(mydate2)); //true  //因为它MyDate类里面重写了Equal方法

 

        }

}

 

 

---------------

 

public class MyDate {

    int year;

    int month;

    int day;

    public int getYear() {

        return year;

    }

    public void setYear(int year) {

        this.year = year;

    }

    public int getMonth() {

        return month;

    }

    public void setMonth(int month) {

        this.month = month;

    }

    public int getDay() {

        return day;

    }

    public void setDay(int day) {

        this.day = day;

    }

    public MyDate(int year, int month, int day) {

        super();

        this.year = year;

        this.month = month;

        this.day = day;

    }

   

    @Override

    public boolean equals(Object obj) {

        //0 .比如 obje 与this 是否是一个对象 。若是,直接返回 true;

        if (this == obj){

            return true;

        }

        if (obj instanceof MyDate){

            MyDate mydate = (MyDate) obj;

           

            return ( ( mydate.year == this.year) &&(mydate.month== this.month )&&( mydate.day == this.day));

        }

        return false;

    }

   

 

}

 

相关文章: