aspose file tools*
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


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Prints 1 why not 2" Watch "Prints 1 why not 2" New topic
Author

Prints 1 why not 2

Muhammad Saghir
Greenhorn

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;
System.out.println(ref2.g());
}
}
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; }
}
Thanks


Saghir SCJP2
Brian Lugo
Ranch Hand

Joined: Nov 10, 2000
Posts: 165
Muhammed,
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.
Brian
[ March 07, 2002: Message edited by: Brian Lugo ]
Rob Ross
Bartender

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.


Rob
SCJP 1.4
Muhammad Saghir
Greenhorn

Joined: Mar 06, 2002
Posts: 6
Thanks Brian and Rob
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Prints 1 why not 2