• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Ron McLeod
  • paul wheaton
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
  • Himai Minh
Bartenders:

Polymorphism confusion

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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");
}
}
 
Ranch Hand
Posts: 2412
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
But note that none of the print methods are overridden.
 
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic