Casting and Instanceof

Quiz Guidelines

 

Multiple Choice Question

QID: 
215

Consider the following classes :

interface I{
}
class A implements I{
}
class B extends A {
}
class C extends B{
}

And the following declarations:

A a = new A();
B b = new B();

Identify options that will compile and run without error.

Select 1 option

A. a = (B)(I)b;
B. b = (B)(I) a;
C. a = (I) b;
D. I i = (C) a;

Multiple Choice Question

QID: 
214

Given the following class definitions :

interface MyIface{};
class A {};
class B extends A implements MyIface{};
class C implements MyIface{};

and the following object instantiations:

A a = new A();
B b = new B();
C c = new C();

Which of the following assignments are legal at compile time?

Select 1 option

A. b = c;
B. c = b; 
C. MyIface i = c; 
D. c = (C) b; 
E. b = a;

Multiple Choice Question

QID: 
213

What will the following code print when run?

class Baap {
public int h = 4;
public int getH() {
System.out.println("Baap " + h);
return h;
}
}   public class Beta extends Baap {
public int h = 44;
public int getH() {
System.out.println("Beta " + h);
return h;
}   public static void main(String[] args) {
Baap b = new Beta();
System.out.println(b.h + " " + b.getH());
Beta bb = (Beta) b;
System.out.println(bb.h + " " + bb.getH());
}
}

Select 1 option

A. Beta 44
4 44
Baap 44
44 44
B. Baap 44
4 44
Beta 44
44 44
C. Beta 44
4 44
Beta 44
4 44
D. Beta 44
4 44
Beta 44
44 44

Multiple Choice Question

QID: 
212

What will be the result of attempting to compile and run class B?

class A{
   final int fi = 10;
}
public class B extends A{
   int fi = 15;
   public static void main(String[] args){
       B b = new B();
       b.fi = 20;
       System.out.println(b.fi);
       System.out.println(  (  (A) b  ).fi  );
   }
}

Select 1 option

A. It will not compile.
B. It will print 10 and then 10
C. It will print 20 and then 20 
D. It will print 10 and then 20 
E. It will print 20 and then 10

Multiple Choice Question

QID: 
211

Consider the following program...

class Super {  }
class Sub extends Super {  }
public class TestClass{
   public static void main(String[] args){
      Super s1 = new Super(); //1
      Sub s2 = new Sub();     //2
      s1 = (Super) s2;        //3
   }
}

Which of the following statements are correct?

Select 1 option

A. It will compile and run without any problems.
B. It will compile but WILL throw Class Cast Exception at runtime.
C. It will compile but MAY throw Class Cast Exception at runtime.
D. It will not compile. 
E. None of the above.

Pages