Leave a Reply 6

Your email address will not be published. Required fields are marked *


Maxtor

Maxtor

D and error in complile n2

Sucuk

Sucuk

So which one is the correct answer????

renko

renko

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

renko

renko

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.