instanceof

자바에서 해당 객체가 어느 클래스 혹은 인터페이스 타입인지 확인하기 위해서 사용하는 연산자이다. 자세한 설명은 아래에.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
public class Main{
    public static void main(String[]args){
        
        /**
         * ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
         * 
         * instanceof 객체 타입을 확인하는데 사용한다.
         * 주로 부모 객체 혹은 자식 객체인지를 확인하는데 이용한다.
         * 
         * 해당 객체 + instanceof + 클래스
         * 
         * ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
         * **/
        
        
        Person personTeacher = new Teacher();
        Person personStudent = new Student();
        
        System.out.println("personTeacher --> Teacher : " + (personTeacher instanceof Teacher));
        System.out.println("personStudent --> Student : " + (personStudent instanceof Student));
        
        System.out.println();
        System.out.println("personTeacher --> Person : " + (personTeacher instanceof Person));
        System.out.println("personStudent --> Person : " + (personStudent instanceof Person));
        
        System.out.println();
        System.out.println("personTeacher --> Student : " + (personTeacher instanceof Student));
        System.out.println("personStudent --> Teacher : " + (personStudent instanceof Teacher));
    
        System.out.println();
        System.out.println((Integer)3 instanceof Integer);
        System.out.println((Double)3.5 instanceof Double);
 
        //  출력내용
        >> personTeacher --> Teacher : true
        >> personStudent --> Student : true
 
        >> personTeacher --> Person : true
        >> personStudent --> Person : true
 
        >> personTeacher --> Student : false
        >> personStudent --> Teacher : false
 
        >> true
        >> true
    }
}
 
interface Person{
    public void eat();
    public void sleep();
    public void walk();
}
 
class Teacher implements Person{
    @Override
    public void eat() {
        // TODO Auto-generated method stub
    }
 
    @Override
    public void sleep() {
        // TODO Auto-generated method stub
    }
 
    @Override
    public void walk() {
        // TODO Auto-generated method stub
    }
}
 
class Student implements Person{
    @Override
    public void eat() {
        // TODO Auto-generated method stub
        
    }
 
    @Override
    public void sleep() {
        // TODO Auto-generated method stub
        
    }
 
    @Override
    public void walk() {
        // TODO Auto-generated method stub
        
    }
}
cs


Posted by doubler
,