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.
D and error in complile n2
So which one is the correct answer????
Answer: D, but not sure!
package q023;
class A {
public void test() {
System.out.println(“A”);
}
}
package q023;
class B extends A{
public void test() {
System.out.println(“B”);
}
}
package q023;
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();
A b3 = (B) b2; //line n1
A b3 = (B) b2; //line n2 => duplicate code!
b1.test();
b3.test();
}
}
Output:
Exception in thread “main” java.lang.Error: Unresolved compilation problem:
Duplicate local variable b3
at q023.C.main(C.java:12)
==================================================
public static void main(String[] args) {
A b1 = new A();
A b2 = new C();
A b3 = (B) b2; //line n1
//A b3 = (B) b2; //line n2 => duplicate code!
b1.test();
b3.test();
}
Output:
Exception in thread “main” java.lang.ClassCastException: q023.C cannot be cast to q023.B
at q023.C.main(C.java:11)
=====================================================
public static void main(String[] args) {
A b1 = new A();
A b2 = new C();
//A b3 = (B) b2; //line n1
//A b3 = (B) b2; //line n2 => duplicate code!
b1.test();
//b3.test();
}
Output:
A
B extends A
C extends A
A b2 = new C();
=> A b3 = (B) b2; this will give a ClassCastException because B and C are not related, although they have the same parents.
This link gives you a good understanding:
http://durgasoftvideos.com/core-java-ocjp-scjp-durga/
=> Ch 5: Core Java With OCJP/SCJP: OOPs by Durga
Lectures OOPs Videos
Video: Core Java With OCJP/SCJP: OOPs(Object Oriented Programming) Part-8||coupling
La B