Given:
What is the result?
A. A
B
B. A C
C. C C
D. A ClassCastException is thrown only at line n1
E. A ClassCastException is thrown only at line n2
Given:
What is the result?
A. A
B
B. A C
C. C C
D. A ClassCastException is thrown only at line n1
E. A ClassCastException is thrown only at line n2
n1 – Cannot cast siblings to eachother
n2 – Cannot re-declare a variable which was already defined in method
I assume in line n1 and/or line n2 is a typo, as they should differ between each other. If remove n1 or n2 compilation will be acceptable but running result will throw “ClassCastException” on n1 or n2
Answer D:
Classes B and C are siblings, so to say, so we cannot cast them to each other. Line 1 attempt to cast class C to class B. So we get the ClassCastException.
Line 2 is duplicate of line 1, so it causes compilation to fail in the first place. Since there is no suitable option in the answers, we are left to option D.
class A{
public void test(){
System.out.println(“a”);
}
}
class B extends A{
public void test(){
System.out.println(“b”);
}
}
public class C extends A{
public void test(){
System.out.println(“c”);
}
public static void main(String[] args) {
A b1=new A ();
A b2=new C ();
b1=(A)b2;
A b3=(B) b2;
A b3=(B) b2;
b1.test();
b3.test();
}
}
Should be E
D: A ClassCastException is thrown only at line n1, but since n2 is identical, there’s a compilation error too.