bugl
bugl
HomeLearnPatternsPathsSearch
HomeLearnPatternsPathsSearch

Loading lesson path

Learn/Java/Java Methods
Java•Java Methods

Java Method Overloading

Flash cards

Review the key moves

1/4
Core idea

What is the main idea behind Java Method Overloading?

Lesson checks

Practice each idea before moving on

Short Mimo-style checks built from this lesson's code, terms, and sequence.

1Quick choice

Which statement best captures the main point of this lesson?

2Fill blank

Complete the missing token from the example code.

___ myMethod(int x)
3Order

Put the learning moves in the order that makes the concept easiest to apply.

Consider the following example, which has two methods that add numbers of different type:
With method overloading , multiple methods can have the same name with different parameters:
Method Overloading

Method Overloading

With method overloading , multiple methods can have the same name with different parameters:

Example

int myMethod(int x)
float myMethod(float x)
double myMethod(double x, double y)

Consider the following example, which has two methods that add numbers of different type:

Example

static int plusMethodInt(int x, int y) {
  return x + y;
}
static double plusMethodDouble(double x, double y) {
  return x + y;
}
public static void main(String[] args) {
  int myNum1 = plusMethodInt(8, 5);
  double myNum2 = plusMethodDouble(4.3, 6.26);
  System.out.println("int: " + myNum1);
  System.out.println("double: " + myNum2);
}

Instead of defining two methods that should do the same thing, it is better to overload one.

In the example below, we overload the plusMethod method to work for both int and double :

Example

static int plusMethod(int x, int y) {
  return x + y;
}
static double plusMethod(double x, double y) {
  return x + y;
}
public static void main(String[] args) {
  int myNum1 = plusMethod(8, 5);
  double myNum2 = plusMethod(4.3, 6.26);
  System.out.println("int: " + myNum1);
  System.out.println("double: " + myNum2);
}

Note

Multiple methods can have the same name as long as the number and/or type of parameters are different.

Previous

Java Return

Next

Java Scope