|
Re: Flaw in inheritance and overloading combination?
|
Posted: Jul 31, 2002 4:44 PM
|
|
Here is the explanation of why you got this compiler error saying : "Method reference is ambiguous". If you just move overTest ( float ) to Base class and overTest (int) to Test class then the code will compile and run fine. Again, if you make overTest in Base and Test "static" then again code will compile and work fine. So, what is the real problem? We need to look into the method invocation process in Java. In case of two methods matching ( not exaclty rather applicable)the more specific method is chosen for invocation. One important thing to mention here is that for all non-static methods of a class there is one extra method argument that is provided by compiler and its name is "this" with its type as same as class type. For example, for overTest ( int i ) in Base class we can think of real overTest(int i ) method as overTest(Base this, int i ) and for overTest ( float f ) in Test class it can be thought as overTest (Test this, float f). Now based on argument passed as 10 there are two methods that are applicable: Base->overTest(int i) Test->overTest(float f) If you try to find out, which method is more specific then you jump to conclusion that Base->overTest(int i) is more specific because int i can be assigned to float f, but not vice-versa. And, according to your conclusion Base->overTest(int i) should be chosen by the compiler. But, this is not the case. We are forgetting the hidden parameter "this" for every non-static methods. Methods signature should be viewed as:
Base->overTest(Base this, int i) Test->overTest(Test this, float f)
Here, Base this cannot be assigned to Test this and at the same time float f cannot be assigned to int i. And, this is why the method reference is ambigous in this case. I think you got the point. Now let us move overTest(float) to Base class and then overTest(int i ) to Test. Now methods signature can be viewed as: Base->overTest(Base this, float f) Test->overTest(Test this, int i)
Now it is clear that Base this and float f cannot be assigned to Test this and int i respectively. However, opposite is true. Therefore. Test-> (int i ) will be called. The same argument applies when you move both methods in Base. Since the "this" arguments will be of the same kind i.e. Base, so int i is the most specific method argument in that case.
So, what is the solution. One has been provided in the previous post by Matt. Others are: make methods static. Of course, then you are not using method overriding rather method hiding. Or, move all methods in one class. Do whatever suits your design and requirements.
Thanks Kishori
Thanks Kishori
|
|