Win a copy of 97 Things Every Java Programmer Should Know this week in the Java in General forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Paul Clapham
  • Jeanne Boyarsky
  • Junilu Lacar
  • Henry Wong
  • Ron McLeod
  • Devaka Cooray
  • Tim Cooke
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Frits Walraven
  • Tim Holloway
  • Carey Brown
  • Piet Souris
  • salvin francis
  • fred rosenberger

mock exam query

Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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.
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.

Don't play dumb with me! But you can try this tiny ad:
Devious Experiments for a Truly Passive Greenhouse!
    Bookmark Topic Watch Topic
  • New Topic