deathshot
deathshot

Reputation: 93

Java overloading a method with two parameters

This problem is about overloading methods and I think I understand the basic idea but I get some weird error "Overloading.java:14". Like my problem is that I don't know how to return two parameters of my method. So I thought maybe convert the method with the two int parameters with toString(), then return it. Something gone miserably wrong. The output have to be following:

a 10

a and b 10, 20

char a

result 97

My problem as it is, is with the "a and b 10, 20", and have not done the "char a" just to make you guys aware. This is not homework. Here is my code so far contains a main class and a helper class:

OverMain Class :

class OverMain {   
     public static void main(String args[]) {   
        Overload overload = new Overload();   
        int result;   
        System.out.println("a " + overload.test(10));  //prints a 10
            System.out.println("a and b " + overload.test(10, 20));  //the method I have trouble with
        result = overload.test('a'); //prints Result 97
        System.out.println("Result " + result);   
     }   
}  

Overload Class:

//The class which is suppose to overload test methods
class Overload {

  public int test(int a) {
    return a;
  }

  public String test(int a, int b) {
    String string = "";
       string = test(a, b).toString();
       return string;
  }

} 

Upvotes: 1

Views: 285

Answers (2)

Mitesh Pathak
Mitesh Pathak

Reputation: 1306

The problem is in your method test(int, int)

public String test(int a, int b) {

  String string = "";
  string = test(a, b).toString(); // Danger
  return string;
}
  • You have a never ending recurrence relation
  • Solution: return a + ", " + b

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1500675

It's not really clear what you're trying to do, but you don't return parameters, and I don't think overloading is really the problem here. To take overloading out of the situation, you can always change the methods to have different names - get it working that way, and then you can always change the names back later and work out any conflicts.

In your case I think you just need:

public String test(int a, int b) {
    return a + ", " + b;
}

In other words, just use string concatenation and the automatic int to String conversion that the compiler will apply in order to use string concatenation.

Note that if your code actually compiled, you'd get a stack overflow because you're calling test(a, b) from test(int a, int b) - it would just call itself forever, until you ran out of stack space.

Upvotes: 6

Related Questions