您好,欢迎访问一九零五行业门户网

在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 parameterdisplay() method with a single parameterdisplay() method with multiple parameters
以上就是在java中,我们可以定义同名的多个方法吗?的详细内容。
其它类似信息

推荐信息