• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question on Overriding

 
chandru ram
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,
I tried the following example
class A {
public void print(int a) {
System.out.println("method from class A accepting int: "+a);
}
public void print(long a) {
System.out.println("method from class A accepting long: "+a);
}
}
class B extends A {
public void print(long a) {
System.out.println("method from class B accepting long: "+a);
}

}
public class Test {
public static void main(String args[]) {
B b = new B();
b.print(5);
}
}
When this program is compiled, there is a compilation error like :
Test.java:23: reference to print is ambiguous, both method print(int) in A and method print(long) in B match
b.print(5);
^
1 error

When we try to do this operation base class alone like A a = new A(); and then a.print(5).it works correctly. the compiler associates the call to the method accepting int as parameter.
but why this doesn't happen when the method is over-ridden?
pls explain.
Thanks in advance,
chandru
 
Wayne L Johnson
Ranch Hand
Posts: 399
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was puzzled, so I copied the example and tried to compile and run it. Guess what? It worked fine, giving me "method from class A accepting int: 5".
I'm running JDK 1.4.2_x on Win2000. What version of the JDK are you using? It may have been a problem in an earlier version of Java which is now fixed ...
 
Joel McNary
Bartender
Posts: 1840
Eclipse IDE Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I believe that it is the case that is is no longer a problem with the current JVM. I think that this same question was asked a few weeks back Marilyn posted a link to a change in the JLS that describes this situation; I can't find that link right now.
Basically, a slight change was make to the rules governing what is more "specific" than what, and now the rules work (more like) what you would expect.
 
Sandeep Jindal
Ranch Hand
Posts: 180
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear Wayne,
Like you, I was also puzzled and tried the example. When i tried, i got the same compile error as Mr Chandru got. And I want to add that i m ruuning JDK1.4.1 on win2K.
So does this mean that the problem is resolved in 1.4.2?
And if it is, then why was the compiler giving error before that? I mean at what point the compiler was confued?

Regards
Sandeep
 
chandru ram
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes this is a bug with previous releases. please see this link for more details:
http://www.sys-con.com/story/?storyid=34292

Regards,
Chandru ram
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic