Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

mock exam query

 
ketki kalkar
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,
Following is a query from javabeat mock exam 11.
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( ); 1.
B o2 = (B) o1; 2.
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 correct option
(1) The progarm will fail to compile
(2) Class cast exception at runtime
(3) It will print 30, 20
(4) It will print 30, 30
(5) It will print 20, 20
answer is 3.

The method to be used depends on class of the object.Here it is an instance method so should it refer to class C for the first part of answer?
Please explain.
 
Gunjan Kumar
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

This is a case of overriding

In first case,
A o1 = new C( ); 1.

This is a object of C and Refers to type A. Since this is a case of overriding, so method will get called according to object type(C), not reference type(A). So C's method will get called.

In second case:
System.out.println(o2.i );
Here o2 refers to B object due to explicit cast. So B's methos get called
and prints 20.
 
Jeremy Botha
Ranch Hand
Posts: 125
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, you're right, the method to be used depends on the class of the object.

Look closely at these lines:


o1 is an instance of C, referenced by a reference variable of type A.
c's method will be called, regardless of whether the reference variables is of type A, B or C.

o2, however, is explicitly cast to an instance of B. Hence, it is an object of type B, thus B's variable i is referenced.

J
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic