Appearance
Method Overloading
In a class, we can define multiple methods. If there is a series of methods with similar functions and only different parameters, then this group of method names can be made into methods with the same name . For example, in the Hello
class, define multiple hello()
methods:
java
class Hello {
public void hello() {
System.out.println("Hello, world!");
}
public void hello(String name) {
System.out.println("Hello, " + name + "!");
}
public void hello(String name, int age) {
if (age < 18) {
System.out.println("Hi, " + name + "!");
} else {
System.out.println("Hello, " + name + "!");
}
}
}
This method has the same name but different parameters, which is called method overloading ( Overload
).
Note: The return value types of method overloads are usually the same.
The purpose of method overloading is that methods with similar functions use the same name, which is easier to remember and therefore easier to call.
For example, the String
class provides multiple overloaded methods indexOf()
to find substrings:
int indexOf(int ch)
: Search according to the Unicode code of the character;int indexOf(String str)
: Search based on string;int indexOf(int ch, int fromIndex)
: Search based on characters, but specify the starting position;int indexOf(String str, int fromIndex)
Find based on a string, but specify the starting position.
Give it a try:
java
// String.indexOf()
public class Main {
public static void main(String[] args) {
String s = "Test string";
int n1 = s.indexOf('t');
int n2 = s.indexOf("st");
int n3 = s.indexOf("st", 4);
System.out.println(n1);
System.out.println(n2);
System.out.println(n3);
}
}
Practise
Add the overloaded method setName(String, String)
to Person
:
java
public class Main {
public static void main(String[] args) {
Person b = new Person();
Person j = new Person();
b.setName("bob");
// TODO: Add overloaded method setName(String, String) to Person:
j.setName("bob", "john");
System.out.println(b.getName());
System.out.println(j.getName());
}
}
class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Summary
Method overloading means that multiple methods have the same method name but different parameters;
The overloaded method should complete similar functions, refer to String
's indexOf()
;
The return value type of overloaded methods should be the same.