Có, chúng ta có thể định nghĩa nhiều phương thức trong một lớp với cùng tên nhưng kiểu tham số khác nhau. Phương thức nào được gọi phụ thuộc vào tham số truyền vào.
Trong ví dụ dưới, có ba phương thức display cùng tên nhưng tham số khác. Tùy tham số, phương thức thích hợp sẽ được gọi.
Ví dụ
public class MethodWthSameNameTest {
public void display() { // phương thức không tham số
System.out.println("display() method with no parameter");
}
public void display(String name) { // phương thức một tham số
System.out.println("display() method with a single parameter");
}
public void display(String firstName, String lastName) { // phương thức nhiều tham số
System.out.println("display() method with multiple parameters");
}
public static void main(String args[]) {
MethodWthSameNameTest test = new MethodWthSameNameTest();
test.display();
test.display("raja");
test.display("raja", "ramesh");
}
}
Kết quả
display() method with no parameter display() method with a single parameter display() method with multiple parameters