-1

I asked on SE how to make a function that accepts different kinds of variables. People have told me to "overload".

My question: how do I use overloading to make a function that will accept multiple data types (int bool string) as it's input?

Also, what are the advantages and disadvantages of overloading? Is it related to "overloading my computer"?

genisome
  • 47
  • 1
  • 1
  • 7

4 Answers4

1

Overloading is a concept that doesn't hurt your computer but sometimes it makes your head hurt. Not really. Overloading is just writing multiple implementations of a method with the same name but different parameter types. It requires the programmer to write code like this. Notice the return types are the same.

public int SomeMethod(int someValue) 
{ //one implementation for ints }
public int SomeMethod(String someValue)
{ //another implementation for strings}

Which method is invoked depends on on the argument type. The method invoked here is the one for integer arguments:

int result = SomeMethod(5);

Another way of doing this is using Generic Methods. This is a little advanced for the question asked, but it might be what you're looking for. The Oracle Java Documentation is a good place to start.

0

Try looking into generic types: https://docs.oracle.com/javase/tutorial/java/generics/boundedTypeParams.html

Eric
  • 85
  • 1
  • 6
0

Overloading is a concept. It will not affect your computer or your code. It is simply the fact of declaring multiple methods in your class with the same name but different arguments.

For example:

private int doSomething(int anInteger) {
   // do something with an integer
}

private int doSomething(float aFloat) {
   // do something with a float
}

Doing this will allow you to use the same method name on different parameter types, but have different method implementation.

Samuel
  • 2,106
  • 1
  • 17
  • 27
-1
public void myFunction(String s){ ... }

public void myFunction(int i){ ... }

public void myFunction(bool b){ ... }

Really you should be able to google "java overloading" or something instead of posting on here for this. Googling is a top developer skill. Read the documentation, or your textbook or something.

Brent Sandstrom
  • 841
  • 10
  • 16