OPEN between Secret

instanceof를 이용한 객체 구별 본문

java/예제

instanceof를 이용한 객체 구별

해가꿈꾸는달 2012. 5. 28. 20:28
반응형

class Person {
 
}

class Student extends Person {
 
}

class Researcher extends Person {
 
}

class Professor extends Researcher {
 
}

 

public class InstanceofExample {

 public static void main ( String [] args) {
      Person jee= new Student();
      Person kim = new Professor();
      Person lee = new Researcher();
  
      if( jee instanceof Student)                                          //jee는 Student 타입이므로 true
           System.out.println("jee는 Student 타입");
  
      if( jee instanceof Researcher)                                    // jee는 Researcher 타입이 아니므로 false
           System.out.println("jee는 Researcher 타입");
  
      if( kim instanceof Student)                                         // kim은 Student 타입이 아니므로 false
           System.out.println("kim는 Student 타입");
  
      if( kim instanceof Professor)                                      // kim은 Professor 타입이므로 true
           System.out.println("kim는 Professor 타입");
  
      if( kim instanceof Researcher)                                   // kim은 Researcher 타입이므로 true
           System.out.println("kim는 Researcher  타입");
  
      if( kim instanceof Person)                                         // kim은 Person 타입이므로 true
           System.out.println("kim는 Person 타입");
  
      if( lee instanceof Professor)                                      // lee는 Professor 타입이 아니므로 false 
           System.out.println("lee는  Professor 타입");
  
      if( "java" instanceof String)                                       // "java"는 String 타입의 인스턴스이므로 true
           System.out.println("\"java\"는 Student 타입");
  
     }
}
----------------------------------------------------------------------------------------------------

Person을 상속받은 클래스들의 관계가 복잡할때 래퍼런스가 어떤 객체를 가르키는지 알아보고자 할때  instanceof를 사용한다.

 

예제 - 명품 java programming -

반응형