2

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.

Mark Rotteveel
110k239 gold badges158 silver badges230 bronze badges
asked Feb 18, 2020 at 13:33
8

3 Answers 3

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.

answered Feb 18, 2020 at 13:48

1 Comment

Ty for the answer. that Is what i was looking for <3
0

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.

answered Feb 18, 2020 at 13:37

Comments

0

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.

answered Feb 18, 2020 at 13:37

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.