• Post Reply Bookmark Topic Watch Topic
  • New Topic

polymorphism question  RSS feed

 
Roy Tock
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've got a question that I'm hoping one of you can answer. All of this goes into MyMain.java:



Now run. The result:

MySuperclass: doing something
MySubclass: doing something else

Now the $64,000 question: Why is doSomething() from MySuperclass invoked, rather than doSomething from MySubclass?
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The two doSomething() methods take different kinds of arguments -- they have different signatures -- so they're not polymorphic, they're overloads. The compiler chooses one at compile time based on the argument list and reference type.

If you change MySuperclass.doSomething() to accept a String argument, you'll see the polymorphic behavior you're expecting!
 
Roy Tock
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Got that. (That's why I added in the doSomethingElse() method.) And you're right, this isn't truly a polymorphism question.

But why would the compiler choose MySuperclass.doSomething()? I would expect that because the underlying object is actually an instance of MySubclass, the called method would be MySubclass.doSomething(). On top of that, the call in main() has a String argument, which would match MySubclass.doSomething(String) method more specifically than MySuperclass.doSomething(Object).

I'm sure I'm thinking about this incorrectly...but I still don't see it.
 
Steven Bell
Ranch Hand
Posts: 1071
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because when overloading the method is chose at compile time based on the type of the reference, not the type of the object.

If you changed it to MySubclass name = new MySubclass();

you would get the subclass methods.
 
Roy Tock
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Got it; thanks! That explains the previous example, and it also explains why



prints this:

MySubclass: doing something with an object
MySubclass: doing something else

. The doSomething(Object) method is chosen at compile time because the reference is to a MySuperclass, but at run time the decision is made to use the subclass's doSomething(Object). Nasty...but now understandable.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!