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 Polymorphism confusion 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 "Polymorphism confusion" Watch "Polymorphism confusion" New topic

Polymorphism confusion

mango ewing

Joined: Sep 28, 2006
Posts: 2
All, I don't get one of the quiz problems -- the code is pasted below, and the result is "super super super super base"
My question is: Object b is of type base, even though it has a superclass-reference. By the definition of polymorphism, the print() method of base should be invoked. Why in this case, it was that of superclass i/o base? Isn't that a violation of polymorphism?


public class overwrite {
public static void main(String[] args) {
superclass a = new superclass();
superclass b = new base();
base c = new derived();
a.print(new base());
b.print(new derived());
b.print(new base());
b.print(new superclass());
c.print(new derived());

class superclass{
void print(superclass s){
class base extends superclass{
void print(base b){
class derived extends base{
static void print(derived d) {
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2398
But note that none of the print methods are overridden.
Alangudi Balaji Navaneethan
Ranch Hand

Joined: Apr 28, 2004
Posts: 42

In first four method calls, you create a reference to superclass and pass base,sub and super objects. But actually you are calling method of superclass. In the last method call you create a reference to base class and call the method of that object...

You did not override print methods... you did not call methods of any derived objects that are reference by superclass variable...

hope you can understand now.

if you think you can you r right<br />if you think you can not you r double right
I agree. Here's the link:
subject: Polymorphism confusion
It's not a secret anymore!