• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Tricky Question on Overriding

 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Predict the O/P . the class compiles and runs perfectly

import java.io.*;
class Poly
{
public static void main(String argv[])
{
A ref1 = new C();
B ref2 = (B) ref1;
System.out.println(ref2.g());
}
}

class A
{
private int f()
{
return 0;
}
public int g()
{
return 3;
}

}

class B extends A
{
private int f()
{
return 1;
}
public int g()
{
return f();
}
}

class C extends B
{
public int f()
{
return 2;
}
}


Please answer to the above : The answer is 1 and not 2 as most of us might have expected . Why ???
 
Enthuware Software Support
Posts: 4832
52
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Which instance method will be called depends on the actual class of the object and not the class of the variable referencing it. Here, the actual object is of class C.
But this happens only when the method is inherited accross the hierarchy. Here, in class B, f() is private and so is not inherited by class C. So, when method g() of class B calls f(), class B's f() is called instead of class C's.
HTH,
Paul.

------------------
Get Certified, Guaranteed!
(Now Revised for the new Pattern)
www.enthuware.com/jqplus
 
Rancher
Posts: 1449
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Private method calls are statically bound. A method will call the private method in the class where it is defined even if the calling method is inherited by a derived class and the derived class defines a method with the same signature as the private method.
Since ref2 is cast to a B the private f() method of B is called not the f() in C.
This information is from a certification notes page by cdesboro that was out on geocities but has apparently moved.
Does anyone know where these notes can be found on the web? They helped me greatly in passing the SCJP test.
John
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic