Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Method overloading trong Java


Method overloading là static polymorphism. Trong overloading, định nghĩa nhiều method cùng tên nhưng parameter khác nhau. Xem ví dụ:

Ví dụ

public class Tester {
    public static void main(String args[]) {
        Tester tester = new Tester();
        System.out.println(tester.add(1, 2));
        System.out.println(tester.add(1, 2, 3));
    }
    public int add(int a, int b) {
        return a + b;
    }
    public int add(int a, int b, int c) {
        return a + b + c;
    }
}

Kết quả

3 6

Ở đây dùng method add() nhận 2 hoặc 3 parameter và hành xử tương ứng. Đây gọi là method overloading hoặc static polymorphism.