Java 中的重载方法?

Overloading methods in Java?

我对 Java 还是有点陌生​​,我可以使用这段代码的一些帮助,到目前为止我写了方法以及每个方法应该做什么,但老实说我不知道​​该怎么做重载效果并使其工作,所以我希望得到一个简单的解释。

import java.util.Scanner;
public class Assignment3 {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
    // TODO Auto-generated method stub
    myMethod();
}
public static void myMethod(){
    System.out.println("Welcome to Java 1 ");

}
public static void myMethod(String msg, int counter){
    System.out.println("Enter your custom messege please: ");
    msg = input.nextLine();

    System.out.println("Please enter how many times do you wish to print the messsege: ");
    counter = input.nextInt();

    for (int i = 0; i <= counter; i++){
        System.out.println(msg);
    }
}
public static void myMethod(int lowerLimit, int upperLimit){

    System.out.println("Please enter a lowerlimit: ");
    lowerLimit = input.nextInt();

    System.out.println("Please enter an upperlimit: ");
    upperLimit = input.nextInt();

    System.out.println("Press 1 for ascending order: ");
    System.out.println("Press 2 for descending order: ");
    System.out.println("Make your selection");
    int user1 = input.nextInt();
    System.out.println("How frequent do you wish the messege to be printed");
    int interval = input.nextInt();

    switch(user1){
    case 1:
        for(int counter = lowerLimit; counter <= upperLimit; counter += interval){
            System.out.println(counter);
        }
        break;
    case 2:
        for(int counter = upperLimit; counter <= lowerLimit; counter -= interval){
            System.out.println(counter);
        }
        break;
        default :
            System.out.println("Something went wrong !!!");
    }

}
public static void myMethod(double number1, double number2){

    number1 = (Math.random() * 100);
    number2 = (Math.random() * 100);
    double product = (number1 * number2);

    System.out.println("The product of " + number1 + " and " + number2 + " is " + product);
}
]

您的 myMethod 方法已经过载。重载方法只是一种可以接受两组或更多组不同参数的方法。 (参见 https://docs.oracle.com/javase/tutorial/java/javaOO/methods.html

例如:

public void foo(int a) {
  System.out.println("Printing out the int " + a);
}

public void foo(double a) {
  System.out.println("Printing out the double " + a);
}

Foo 有两种可能的参数集,一种接受 int,另一种接受 double。现在,如果您这样做:

int a = 10;
double b = 10.5;

foo(a);
foo(b);

会 return :

Printing out the int 10
Printing out the double 10.5

上面 post 有你的答案,你的 myMethod 方法已经重载,但是方法重载是一个允许 class 有两个或更多同名方法的特性,如果它们的参数列表是不同的。 您的方法接受具有不同数据类型的不同参数

回复您的评论:

您只需在您的主程序中调用另外两个 "myMethod",并使用它们各自的签名:

    public static void main(String[] args) {
        // Call without argument
        myMethod();

        // Call with String and integer
        myMethod("test", 42);

        // Call with Integer and Integer
        myMethod(42, 666);
    }

届时将调用合适的。这是否回答了您的问题?