• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

Overloading/Overriding Method Names

 
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
One of the answer in a mock exam for
Legal reuse of method names:
-In subclass with same arguments with different return types.
I dont think that it is correct answer. I tried a sample code which gives a compile time error:
<CODE>
public class Q8 {
public int amethod()
{
return -1;
}
}
class Q9 extends Q8
{
public String amethod()
{
return "Not Possible";
}
}
</CODE>
Q8.java:17: The method java.lang.String amethod() declared in class Q9 cannot override the method of the same signature declared in class Q8. They must have the same return type.
Any suggestions?
 
Ranch Hand
Posts: 1070
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Overriding methods must have the same signature, that is the same argument types and the same return type. They can have different access modifiers as long as the access is not more restrictive, like overriding a protected method with a private method. Overrding method can also not throw checked exceptions not thrown in the method that is being overridden.
With overloading, the rules are much more relaxed. Basically, you can't have two methods with the same argument list, but all else is fair. Can return different types, can throw different exceptions, can have differnt modifiers. Not good practice to make them different, but is allowed as it really is a different method just has the same name.
Bill
 
reply
    Bookmark Topic Watch Topic
  • New Topic