Casting and Instanceof

Quiz Guidelines


Multiple Choice Question


Consider the following class hierarchy:
1, B2
1, C2

(B1 and B2 are subclasses of A and C1, C2 are subclasses of B1) Which of the following statements are correct? Assume that objectOfA, objectOfC1, etc. are objects of classes A and C1 respectively.

Select 1 option

A. objectOfC2 instanceof B2 will return true.
B. objectOfC1 instanceof B1 will return true.
C. objectOfA instanceof B1 will return true.
D. C1 c1 = objectOfA; is a valid statement.
E. B1 b1 = objectOfB2; is a valid statement.

Multiple Choice Question



interface I { }
class A implements I{
    public String toString(){ return "in a"; }
class B extends A{
    public String toString(){ return "in b"; }
public class TestClass {
    public static void main(String[] args) {
        B b = new B();
        A a = b;
        I i = a;

What will be printed when the above code is compiled and run?

Select 1 option

A. in i
in a
in b
B. I
in b
C. in a
in a
in b
D. in a
in b
in b
E. in b
in b
in b

Multiple Choice Question


What will be the output of compiling and running the following program:

class TestClass implements I1, I2{
public void m1() { System.out.println("Hello"); }
public static void main(String[] args){
TestClass tc = new TestClass();
( (I1) tc).m1();
}  }interface I1{
int VALUE = 1;
void m1();
}interface I2{
int VALUE = 2;
void m1();

Select 1 option

A. It will print Hello.
B. There is no way to access any VALUE in TestClass.
C. The code will work fine only if VALUE is removed from one of the interfaces.
D. It will not compile.
E. None of the above.

Multiple Choice Question


Given the following definitions and reference declarations:

interface I1 { }
interface I2 { }
class C1 implements I1 { }
class C2 implements I2 { }
class C3 extends C1 implements I2 { }
C1 o1;
C2 o2;
C3 o3;

Which of these statements are legal?

Select 3 options

A. class C4 extends C3 implements I1, I2 { }
B. o3 = o1;
C. o3 = o2;
D. I1 i1 = o3; I2 i2 = (I2) i1;
E. I1 b = o3;

Multiple Choice Question


Consider the following code:

interface Flyer{ String getName(); }
class Bird implements Flyer{
public String name;
public Bird(String name){ = name;
}public String getName(){ return name; }
class Eagle extends Bird {
public Eagle(String name){
}public class TestClass {
public static void main(String[] args) throws Exception {
Flyer f = new Eagle("American Bald Eagle");          //PRINT NAME HERE
}  }

Which of the following lines of code will print the name of the Eagle object?

Select 3 options

A. System.out.println(;
B. System.out.println(f.getName());
C. System.out.println(((Eagle)f).name);
D. System.out.println(((Bird)f).getName());
E. System.out.println(;
F. System.out.println(Eagle.getName(f));