Search code examples
javaparameter-passingsubclassargs

Why can't I use (String arg, arg2) instead of (String arg, String arg2) for my method?


I can pass two values to a method using this code in the Subclass:

try
{
    echo(args[0], args[1]);
}
catch (Exception e)
{
    System.out.println("Argument required");
}

and this code in the Superclass:

public static void echo(String arg, String arg2)
{
    try
    {
        System.out.println("You entered: " + arg + " and " + arg2);
    }
    catch (Exception e)
    {
        System.out.println("Argument required");
    }

My question is why must I declare the string variables arg and arg2 by typing String twice? They are both of type String so couldn't I just write (String arg, arg2)?


Solution

  • You just can't. That's how the language was designed.

    A choice was made that method signatures should work in the way they do. It could have been designed differently to support this (for example, golang does).

    But this is how Java is, and it seems vastly unlikely that it would ever be changed to support it.