Java/디딤돌 Java 언어 Part1

[Java 소스] Object 클래스 equals 메서드 재정의

언제나휴일 2016. 12. 22. 13:11
반응형

[Java 소스] Object 클래스 equals 메서드 재정의


MyData.java

MyInt.java

Program.java



//equals 메서드를 재정의하지 않은 MyData 클래스

public class MyData {

        int num;

        public MyData(int num){

               this.num = num;

        }

}



//equals 메서드를 재정의한 MyInt 클래스

public class MyInt {

        int value;

        public MyInt(int value){

               this.value = value;

        }

        public boolean equals(Object obj){

               if(obj instanceof MyInt){

                       MyInt mi = (MyInt)obj;

                       return value == mi.value;

               }

               return false;

        }

}


//equals 메서드 재정의

public class Program {

        public static void main(String[] args){

               MyData md1 = new MyData(1);

               MyData md2 = new MyData(1);

               System.out.println(md1.equals(md2));

               System.out.println(md1==md2);

               MyInt mi1 = new MyInt(1);

               MyInt mi2 = new MyInt(1);

               System.out.println(mi1.equals(mi2));

               System.out.println(mi1==mi2);

        }

}


//안전한 하향 캐스팅 

public class Program {

        static void foo(Musician musician){

               if(musician instanceof Pianist){

                       Pianist pianist = (Pianist)musician;                  

                       pianist.Tunning();

               }

               musician.Play();

        }

        public static void main(String[] args){

               Musician musician = new Drummer();

               foo(musician);

               musician = new Pianist();

               foo(musician);

        }

}


실행 결과

false

false

true

false



본문

[Java] 5.6.1 equals 메서드 (Object 클래스)

학습에 도움이 되시면 ebook 구입(판매가 3000, ebook)하여 소장하시면 감사하겠습니다.





반응형