aspose file tools
The moose likes Java in General and the fly likes Tricky question about polymorphism Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Tricky question about polymorphism" Watch "Tricky question about polymorphism" New topic
Author

Tricky question about polymorphism

doni klauz
Greenhorn

Joined: Jul 21, 2004
Posts: 6
Hi,

I've encounter the following suprising behaviuor with polymorphism and I need someone to explain it to me.

This is simple example :

abstract Class A
{
void test(A a)
{
System.out.println("You are in A");
}
}

Class B extends A
{
void test(B b)
{
System.out.println("You are in B");
}
}



A b1 = new B();
A b2 = new B();
b1.test(b1);

result:

You are in A
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24054
    
  13

Hi Doni,

Welcome to JavaRanch!

The short answer is that there's no polymorphism here. The two different "test" methods have different argument lists, so they are not polymorphic; they're said to be overloaded. It's up to the compiler to decide which of a set of overloaded methods is called, and the compiler looks only at the type of the variable on which the method is called. In contrast, the choice among polymorphic methods is made at runtime based on the actual type of the object.

In any event, here, the compiler sees only that the variable is of type "A", and it looks for a method "test" in "A" that it can call with an argment of type "B", and finds one, and calls it.

Now, if you change the argument type of B.test() to be "A", then you'd see polymorphic behavior. Try it!


[Jess in Action][AskingGoodQuestions]
Corey Hollaway
Greenhorn

Joined: Jul 21, 2004
Posts: 11
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24054
    
  13


// Because the test in myA should only accept (new A()'s)
// Instances of the A class should be the only objects
// that could enter the A.test(A a) method


But note that class B extends class A, and therefore, by definition, a B is an A. An instance of B can correctly be passed to either A.test(A) or B.test(B); an instance of A could only be passed to A.test(A).
[ July 22, 2004: Message edited by: Ernest Friedman-Hill ]
Corey Hollaway
Greenhorn

Joined: Jul 21, 2004
Posts: 11
I see now, thank you
[ July 22, 2004: Message edited by: Corey Hollaway ]
doni klauz
Greenhorn

Joined: Jul 21, 2004
Posts: 6
Thanks
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Tricky question about polymorphism
 
Similar Threads
Question about instance variables
about overloading
Data Hiding
TYPE CAST
overriding cofusion