我们可以在Java中的同名类中定义多个方法吗?
是的,我们可以在一个类中定义多个具有相同名称但具有不同类型参数的方法。要调用哪种方法将取决于传递的参数。
在下面的示例中,我们定义了三种名称相同但参数不同的显示 方法。根据参数,将调用适当的方法。
示例
public class MethodWthSameNameTest {
public void display() { // method with no parameters
System.out.println("display() method with no parameter");
}
public void display(String name) { // method with a single parameter
System.out.println("display() method with a single parameter");
}
public void display(String firstName, String lastName) { // method with multiple parameters
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");
}
}输出结果
display() method with no parameter display() method with a single parameter display() method with multiple parameters
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短