File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Polymorphism confusion

 
mango ewing
Greenhorn
Posts: 2
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2399
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But note that none of the print methods are overridden.
 
Alangudi Balaji Navaneethan
Ranch Hand
Posts: 42
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic