수업(국비지원)/Java
[Java] chap7 : 클래스의 관계 - Instanceof연산자
byeolsub
2023. 4. 15. 23:46
- Instanceof연산자
instanceof 연산자 : 객체와 참조변수의 관계를 알려주는 연산자
if (참조변수 instanceof 객체자료형)
true : 참조변수가 참조하는 객체는 객체자료형으로 형변환이 가능함
false : 참조변수가 참조하는 객체는 겍체자료형으로 형변환이 불가능함
📌
package chap7;
class Super3{
int x = 10;
void method() {
System.out.println("Super3 메서드");
}
}
class Child3 extends Super3{
int x = 20;
int y = 100;
void method() {
System.out.println("Child3 메서드");
}
}
public class InstanceofEx1 {
public static void main(String[] args) {
/* Super3 s = new Super3();
//에러를 내지 않기 위해 조건 추가
Child3 c;
// Child3 c = (Child3)s; //ClassCastException 예외 발생
*
* s 참조변수가 참조하는 객체를 Child3타입으로 형변환 가능?
if(s instanceof Child3) { //얘는 결과에 나오지 않는다. why? 값이 없으니까
c = (Child3)s;
System.out.println("s 객체는 Child3 타입의 참조변수로 참조 가능");
System.out.println("s 객체는 Child3 객체임");
}
if(s instanceof Super3) {
System.out.println("s 객체는 Super3 타입의 참조변수로 참조 가능");
System.out.println("s 객체는 Super3 객체임");
}
*/
Super3 s = new Child3(); //이렇게 하면 모든 결과 산출됨
Child3 c;
if(s instanceof Child3) {
c = (Child3)s;
System.out.println("s 객체는 Child3 타입의 참조변수로 참조 가능");
System.out.println("s 객체는 Child3 객체임");
System.out.println(c.x); //20
System.out.println(c.y); //100
c.method(); //Child3 메서드
}
if(s instanceof Super3) {
System.out.println("s 객체는 Super3 타입의 참조변수로 참조 가능");
System.out.println("s 객체는 Super3 객체임");
System.out.println(s.x); //10
//System.out.println(s.y); - 오류.
// y멤버는 Super3의 멤버가 아님.
// (자손 타입의 멤버에는 접근 안되서)
s.method(); //Child3 메서드
//(메서드는 객체에 최종 오버라이드 된 메서드가 출력되므로)
}
/*모든 클래스는 Object클래스를 상속 받는다.
=> 모든 객체는 Object객체를 포함한다.
=> 모든 객체는 Object타입의 참조변수로 참조가 가능하다.
*/
if(s instanceof Object) {
System.out.println("s 객체는 Object 타입의 참조변수로 참조 가능");
System.out.println("s 객체는 Object 객체임");
Object o =s;
//모두 오류. System.out.println(o.x); //Object의 멤버가 아니다.
// System.out.println(o.y);
// o.method();
}
}
}