WHAT IS METHOD OVERLOADING ?

Overloaded methods let you reuse the same method name in a class, but with
different arguments.
EXAMPLE:
class Demo{
int sum(int x,int y){return x+y;}
int sum(int x,int y,int z){return x+y+z;}
public static void main(String[] args){
System.out.println(sum(4,5)+""+sum(4,5,6));
}
}

RULES OF METHOD OVERLOADING:

■ Overloaded methods MUST change the argument list.
■ Overloaded methods CAN change the return type.
■ Overloaded methods CAN change the access modifier.
■ Overloaded methods CAN declare new or broader checked exceptions.

Be careful to recognize when a method is overloaded rather than
overridden.
You might see a method that appears to be violating a rule for overriding, but
that is actually a legal overload, as follows:

public class Foo {
public void doStuff(int y, String s) { }
public void moreThings(int x) { }
}
class Bar extends Foo {
public void doStuff(int y, long s) throws IOException { }
}


SEE THE BELOW CODE:


public class Foo {
void doStuff() { }
}
class Bar extends Foo {
void doStuff(String s) { }
}
The above method is overloaded but not overridden by a subclass.


The following methods are legal overloads of the changeSize() method:
public void changeSize(int size, String name) { }
public int changeSize(int size, float pattern) { }
public void changeSize(float pattern, String name)
throws IOException { }

No comments:

Post a Comment