Overloaded method area has 2 versions in the class hierarchy.What I know about overloading is that during compilation of the source code, depending upon the type of arguments passed and the type of reference,appropriate method is called.I have also read somewhere that when more than one method matches method call signature,the most specific implementation of the method is called.Is it true in case of overloaded as well as overriding methods...am I confusing between two different things?Why is it that we are getting this error?According to me method area(int,int) from class Rectangle should be called.
D:\Java\EditPlus 2>javac Test.java Test.java:15: reference to area is ambiguous, both method area(int,int) in Recta ngle and method area(long,long) in Square match System.out.println(r.area(5 , 4)); ^ 1 error
The compiler tells me <B>The method area(long, long) is ambiguous for the type Square</B>
The declared type of <B>r</B> is Square, therefore the method <B>area</B> from both Square as well as its superclass Rectangle are applicable.
Now since the arguments to the method area are integer literals, the more specific of the two methods is applicable.
Here the more specific of two is that of the Square class that is area(int, int) is more applicable, as 5 and 4 both are integer literals.
We know that a method invocation can widen an argument of type int to match a method parameter of type long so any argument that can be passed to area(int, int) can also be passed to area(long, long) without generating a compile-time error. Since both methods are applicable, the more specific of the two, area(int,int) is chosen over the less specific area(long,long).
Philip could you please explain the statement quoted below in context to what I said above, and correct me if I am wrong.
By the way, the result was what you would expect: the superclass version of the method executed.
Joined: Jan 09, 2004
I compiled and exceuted the program on Java version 1.5, the java -version told me
java version "1.5.0_02" Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_02-b64) Java HotSpot(TM) Client VM (build 1.5.0_02-b64, mixed mode, sharing)
It compiled fine and gave me an output of 20 which is the area method of the Rectangle class.
Is there problem with the versions or what, but again Amit did compile it with Java 1.4.2.
Joined: Mar 14, 2003
ya it compiled and on java -version command it prints
D:\java_prac>java -version java version "1.4.2" Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.2-b28) Java HotSpot(TM) Client VM (build 1.4.2-b28, mixed mode)
................ anyway ..i just wana ask that all program which run on 1.4.2 will run on jdk 1.5 ??? in addition to what jdk 1.5 feature brings ?