Home » Java » Java: switching 2 methods parameter(different type) to use overloading-Exceptionshub

Java: switching 2 methods parameter(different type) to use overloading-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

(Sorry for bad english)
Hi, i’m a High school student, i studied a little bit of Java by myself.
My teacher asked if you can write 2 methods with switched but same parametrer. Ex:

public void method (String arg1, int arg2){
}

public void method(int arg1, String arg2){
}

..
I said yes, the teacher said that i dont know what overloading means but i tested and It worked and then She said “JDK has a bug” and She got mad at me.

Please i need a super and complete question.

How to&Answers:

As mentioned in the official Oracle Java tutorial:

Java can distinguish between methods with different method signatures

On the same page, “method signature” is defined as

Two of the components of a method declaration comprise the method signature—the method’s name and the parameter types.

Since the parameter types are a list, they also have a fixed order (Unlike e.g. a set).

Thus two parameter lists with the same types (But a different order) are considered different parameter type lists, which in turn allows you to declare two methods with the same name and these two parameter type lists without causing compile time errors.

Edit: For more details refer to the Java Language Specification, chapter 8.4.2.

Answer:

Overloading allows different methods to have the same name, but different signatures where the signature can differ by the number of input parameters, or type of input parameters, or order of input parameters.

Answer:

If you are talking about methods on same class, it’s possible in Java and is legit:

public class Test {

    public static void main(String[] args) {
        Test test = new Test();

    }

    public void method (String arg1, int arg2){
    }

    public void method(int arg1, String arg2){
    }
}

This works because two methods have same name, but differnt type for parameters, so for Java there are two different methods.