File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes A question about runtime polymorphism. 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 "A question about runtime polymorphism." Watch "A question about runtime polymorphism." New topic

A question about runtime polymorphism.

Dmitry Zhuravlev
Ranch Hand

Joined: Apr 14, 2010
Posts: 93
Here is the code:

And here is the output:

I wonder why it doesn't print B at second and third lines?
Sridhar Gudipalli
Ranch Hand

Joined: Nov 02, 2005
Posts: 120
Because class A's printthem() method doesnot know anything about class B's printit() method as A's printit() method is private.

Sridhar Gudipalli|SCJP 6.0
SCWCD objectives
Ankit Garg

Joined: Aug 03, 2008
Posts: 9466

As Sridhar said, printit method in A is private and private methods are not overridden so the call to printit is not polymorphic as printit in B doesn't override printit of A...

SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Jim Hoglund
Ranch Hand

Joined: Jan 09, 2008
Posts: 525
So just to remind myself:
1) Private methods are not overridden / polymorphic
2) Static methods are not overridden / polymorphic

Jim ... ...

Sahil Kapoor
Ranch Hand

Joined: Sep 12, 2009
Posts: 316
1) Class B's printit() method is NOT overriding Class A's printit() method because of the fact that Class A's method is Private.

2) Polymorphism applies only to overriden methods and not overloaded or redefined methods.

3) Had it been the case that Class A defines printit() method to be public , then the output at second line would definitely be B, because at that time Class B overrides prinit() method and polymorphism applies to it.

Thanks !!!

SCJP 6.0 96%

(Connecting the Dots ....)
I agree. Here's the link:
subject: A question about runtime polymorphism.
It's not a secret anymore!