File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Tricky Question on Overriding 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 "Tricky Question on Overriding" Watch "Tricky Question on Overriding" New topic
Author

Tricky Question on Overriding

Dinesh Massand
Greenhorn

Joined: Nov 23, 2000
Posts: 5
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

Joined: Sep 23, 2000
Posts: 3293
    
    7
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


Enthuware - Best Mock Exams and Questions for Oracle/Sun Java Certifications
Quality Guaranteed - Pass or Full Refund!
John Wetherbie
Rancher

Joined: Apr 05, 2000
Posts: 1449
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


The only reason for time is so that everything doesn't happen all at once.
- Buckaroo Banzai
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Tricky Question on Overriding