• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Tricky Question on Overriding

 
Dinesh Massand
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • 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 ???
 
Paul Anilprem
Enthuware Software Support
Ranch Hand
Posts: 3711
10
  • Mark post as helpful
  • send pies
  • 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
 
John Wetherbie
Rancher
Posts: 1449
  • Mark post as helpful
  • send pies
  • 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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic