티스토리 뷰

Given

class Base{
public void test() {
System.out.println("Base ");
}
}

class DerivedA extends Base{
public void test() {
System.out.println("DerivedA ");
}
}

class DerivedB extends DerivedA {
public void test() {
System.out.println("DerivedB ");
}
public static void main(String[] args) {
Base b1=new DerivedB();
Base b2=new DerivedA();
Base b3=new DerivedB();
b1=(Base)b3;
Base b4=(DerivedA)b3;
b1.test();
b4.test();
}
}

What is the result?

A. Base

DerivedA

B. Base

DerivedB

C. DerivedB

DerivedB

D. DerivedB

DerivedA

E. A ClassCastException is thrown at runtime.

 

정답: C

해설:

아래코드를 보면 이해가 빠를듯.

 

 

 

class Base{
public void test() {
System.out.println("Base ");
}
}

class DerivedA extends Base{
public void test() {
System.out.println("DerivedA ");
}
}

class DerivedB extends DerivedA {
public void test() {
System.out.println("DerivedB ");
}
public static void main(String[] args) {
Base b1=new DerivedB();
Base b2=new DerivedA();
Base b3=new DerivedB();
System.out.println(b1);
System.out.println(b2);
System.out.println(b3);
b1=(Base)b3;
Base b4=(DerivedA)b3;
System.out.println(b1);
System.out.println(b4);
b1.test();
b4.test();
}

} class Base{
public void test() {
System.out.println("Base ");
}
}

class DerivedA extends Base{
public void test() {
System.out.println("DerivedA ");
}
}

class DerivedB extends DerivedA {
public void test() {
System.out.println("DerivedB ");
}
public static void main(String[] args) {
Base b1=new DerivedB();
Base b2=new DerivedA();
Base b3=new DerivedB();
System.out.println("b1="+b1);
System.out.println("b2="+b2);
System.out.println("b3="+b3);
b1=(Base)b3;
Base b4=(DerivedA)b3;
System.out.println("b1="+b1);
System.out.println("b4="+b4);
b1.test();
b4.test();
}
}

결과:

b1=DerivedB@15db9742
b2=DerivedA@6d06d69c
b3=DerivedB@7852e922
b1=DerivedB@7852e922
b4=DerivedB@7852e922
DerivedB 
DerivedB 

즉, 결국에는 DerivedB를 가리키는 것을 볼 수 있다.

Base b3=new DerivedB(); 여기서 b3는 DerivedB를 가리키고 있고 

b1=(Base)b3; 여기서 b3를 b1에 대입하니 b1은 DerivedB를 가리키고 있고 (b3가 DerivedB 니까..)
Base b4=(DerivedA)b3; b3를 b4에 대입하니 b4는 DerivedB를 가리키고 있다. (b3가 DerivedB 니까..)

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/01   »
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
글 보관함