'Switching 2 methods parameter(different type) to use overloading
I'm a High school student, I studied a little bit of Java by myself. My teacher asked if you can write two methods with switched but same parameters. For example:
public void method (String arg1, int arg2){
}
public void method(int arg1, String arg2){
}
I said yes, the teacher said that I don't know what overloading means, but I tested and it worked, and then she said "JDK has a bug" and she got mad at me.
I need a super and complete answer.
Solution 1:[1]
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.
Solution 2:[2]
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.
Solution 3:[3]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Nightara |
Solution 2 | Uladzislau Kaminski |
Solution 3 | Vokail |