Method overloading giúp tạo nhiều method cùng tên để làm hành động tương tự trên các kiểu parameter khác nhau.
Chúng ta có thể dùng type promotion khi biến cùng kiểu tương tự. Type promotion tự động promote giá trị lower range sang higher range. Ví dụ, byte variable gán cho int variable. Byte sẽ type promoted thành int. Trong trường hợp muốn cộng hai số có thể là byte, short hoặc int, ta dùng single method. Xem ví dụ:
Ví dụ
public class Tester {
public static void main(String args[]) {
Tester tester = new Tester();
byte a = 1, b = 2;
short c = 1, d = 2;
int e = 1, f = 2;
System.out.println(tester.add(a, b));
System.out.println(tester.add(c, d));
System.out.println(tester.add(e, f));
}
public int add(int a, int b) {
return a + b;
}
}
Kết quả
3 3 3