• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Overloading vs Overriding

 
Gaia Nathan
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is it possible to overload methods across classes? I tried out this code, and it works fine:
import java.io.*;
class Super
{
int methodOne( int a, long b ) throws IOException {
// code that performs some calculations
return a;
}
float methodTwo( char a, int b ) {
// code that performs other calculations
float f= 0;
return f;
}
}
public class Test11 extends Super {
public static void main(String args[]) {
Test11 t11 = new Test11();
t11.methodTwo(5);
}
void methodTwo(int f){
System.out.println("Overloaded method: "+f);
}
}
Output:
Overloaded method: 5
Does this mean that the compiler takes methodTwo() in class Test11 as an overloaded method? If I change the header of
t11.methodTwo to "float methodTwo( char x, int z )" does it mean that the compiler now takes t11.methodTwo as an overriding method?
<confused> Thanks in advance
 
Bosun Bello
Ranch Hand
Posts: 1511
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, it's possible to overload methods accross sub/super class. Your assumptions are correct...a method in a subclass with the same name but different signature from the method in the superclass, will overload the method inthe superclass. If the signature, return type and name matches the method in the superclass, then it will override it.


------------------
Bosun
 
Gaia Nathan
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Bosun,
Thanks for your reply. I'm clear about it now.
If we then wish to use the overloaded super class method in the
subclass, do we call it like this:
"super.methodTwo('c',7);" (providing that the method in the super class is not declared private) ?
If we wish to use the overloaded subclass method in the subclass, would we call it like this:
"this.methodTwo(2.3);" ? (regardless of its access modifier)
Sorry for being so tedious. Thanks again.
 
Mike Curwen
Ranch Hand
Posts: 3695
IntelliJ IDE Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The 'this' keyword is not required in the case where you are calling any method from within the class in which it's defined (whether it overrides a super classes' method or not)
 
Gaia Nathan
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ohhh..okay..Thanks again.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic