aspose file tools
The moose likes Java in General and the fly likes polymorphism question Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "polymorphism question" Watch "polymorphism question" New topic
Author

polymorphism question

Roy Tock
Ranch Hand

Joined: Jul 16, 2001
Posts: 83
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
Marshal

Joined: Jul 08, 2003
Posts: 24041
    
  13

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!


[Jess in Action][AskingGoodQuestions]
Roy Tock
Ranch Hand

Joined: Jul 16, 2001
Posts: 83
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

Joined: Dec 29, 2004
Posts: 1071
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

Joined: Jul 16, 2001
Posts: 83
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.
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: polymorphism question
 
Similar Threads
Compiler errors at line 7, 15 & 13
Whats wrong with the protected method?
Doubt in Static Methods
abstract and interfaces
Peers in AWT