Casting and Instanceof

Quiz Guidelines

 

Multiple Choice Question

QID: 
210

Which statements, when inserted at line 1, will cause an exception at run time?

class B {} 
class B1 extends B {} 
class B2 extends B {} 
public class ExtendsTest{  
public static void main(String args[]){     
B b = new B();     
B1 b1 = new B1();     
B2 b2 = new B2();     // insert statement here 
 }
 }

Select 1 option

A. b = b1; 
B. b2 = b; 
C. b1 = (B1) b; 
D. b2 = (B2) b1; 
E. b1 = (B) b1;

Multiple Choice Question

QID: 
209

What will be the result of attempting to compile and run the following program?

public class TestClass{   
public static void main(String args[ ] ){      
A o1 = new C( );      
B o2 = (B) o1;      
System.out.println(o1.m1( ) );      
System.out.println(o2.i );   } } 
class A { int i = 10;  int m1( ) { 
return i; } }
 class B extends A { int i = 20;  int m1() { 
return i; } } 
class C extends B { int i = 30;  int m1() {
 return i;  } }

Select 1 option

A. The program will fail to compile. 
B. Class cast exception at runtime. 
C. It will print 30, 20. 
D. It will print 30, 30. 
E. It will print 20, 20. 

Multiple Choice Question

QID: 
208

Consider the following class hierarchy

class A{  
public void m1() {   } } 
class B extends A{  
public void m1() {   } } 
class C extends B{   
public void m1(){      /*  //1      ... lot of code.      */   } }

Select 2 options 

A. You cannot access class A's m1() from class C for the same object ( i.e. this). 
B. You can access class B's m1() using super.m1() from class C. 
C. You can access class A's m1() using ( (A) this ).m1() from class C. 
D. You can access class A's m1() using super.super.m1() from class C. 

Multiple Choice Question

QID: 
207

Which is the first line that will cause compilation to fail in the following program?

// Filename: A.java

class A{
public static void main(String args[]){
A a = new A();
B b = new B();
a = b;  // 1
b = a;  // 2
a = (B) b; // 3
b = (B) a; // 4   } }
class B extends A { }

Select 1 option

A. At Line 1. 
B. At Line 2. 
C. At Line 3. 
D. At Line 4. 
E. None of the above. 

Multiple Choice Question

QID: 
206

Consider :
class A { public void perform_work(){} }
class B extends A { public void perform_work(){} }
class C extends B { public void perform_work(){} }

How can you let perform_work() method of A to be called from an instance method in C?

Select 1 option

A. ( (A) this ).perform_work( );
B. super.perform_work( );
C. super.super.perform_work( );
D. this.super.perform_work( );
E. It is not possible.

Pages