Meaningless Drivel is fun!
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Prints 1 why not 2 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 "Prints 1 why not 2" Watch "Prints 1 why not 2" New topic

Prints 1 why not 2

Muhammad Saghir

Joined: Mar 06, 2002
Posts: 6
can someone explain it is not going into my head

public class Poly {
public static void main(String args[]) {
PolyA ref1 = new PolyC();
PolyB ref2 = (PolyB)ref1;
class PolyA {
private int f() { return 0; }
public int g() { return 3; }
class PolyB extends PolyA {
private int f() { return 1; }
public int g() { return f(); }
class PolyC extends PolyB {
public int f() { return 2; }

Saghir SCJP2
Brian Lugo
Ranch Hand

Joined: Nov 10, 2000
Posts: 165
If you want it to print 2 then make the method f() public/protected/default in class PolyB. In this case the method f() in class PolyB will be overridden in class PolyC.
[ March 07, 2002: Message edited by: Brian Lugo ]
Rob Ross

Joined: Jan 07, 2002
Posts: 2205
The runtime object in ref2 is a PolyC object. But that class has no g() method, so the g() method invoked will be the version inherited from PolyB().
PolyB simply returns the value from the method f(). However, at the scope where g() is defined, f() is a private method. Private methods are not inherited by subclasses. In fact, private methods are implicitly final. Because of this, there is no polymorphic call made. The f() method in PolyB gets executed, which returns a 1.
The methods f() in PolyB and PolyC are totally unrelated - they are not overridden, nor are they hidden. The f() method from PolyB does not exist in PolyC, and the f() method in PolyC is an implementation detail of the class that just happens to share the same name as a method in the superclass - but this is mere coincidence.

SCJP 1.4
Muhammad Saghir

Joined: Mar 06, 2002
Posts: 6
Thanks Brian and Rob
I agree. Here's the link:
subject: Prints 1 why not 2
It's not a secret anymore!