permaculture playing cards
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes mock exam query Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "mock exam query" Watch "mock exam query" New topic

mock exam query

ketki kalkar
Ranch Hand

Joined: May 09, 2007
Posts: 36
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

Joined: Mar 26, 2007
Posts: 74

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.

Gunjan Kumar
SCJP 1.5
Jeremy Botha
Ranch Hand

Joined: Feb 16, 2005
Posts: 125
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.


McFinnigan? Never heard of him. Nobody here but us chickens...<br /> <br />SCJP for Java 1.4<br />SCJD for Java 5.0
I agree. Here's the link:
subject: mock exam query
It's not a secret anymore!