| Author |
Polymorphism confusion
|
mango ewing
Greenhorn
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? Thanks 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){ System.out.println("super"); } } class base extends superclass{ void print(base b){ System.out.println("base"); } } class derived extends base{ static void print(derived d) { System.out.println("derive"); } }
|
 |
Keith Lynn
Ranch Hand
Joined: Feb 07, 2005
Posts: 2341
|
|
|
But note that none of the print methods are overridden.
|
 |
Alangudi Balaji Navaneethan
Ranch Hand
Joined: Apr 28, 2004
Posts: 42
|
|
Yes, 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
|
 |
 |
|
|
subject: Polymorphism confusion
|
|
|