• 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 ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Junilu Lacar
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Knute Snortum
  • Tim Cooke
  • Devaka Cooray
Saloon Keepers:
  • Ron McLeod
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Ganesh Patekar

mock exam query

 
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.
 
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.
 
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
 
I can't renounce my name. It's on all my stationery! And hinted in this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!