如果有一系列方法,它们的功能都是类似的,只有参数有所不同,那么,可以把这一组方法名做成同名方法
例如,在Hello
类中,定义多个hello()
方法:
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 + "!");
}
}
}
这种方法名相同,但各自的参数不同,称为方法重载(Overload
)
注意:方法重载的返回值类型通常都是相同的。
方法重载的目的是,功能类似的方法使用同一名字,更容易记住,因此,调用起来更简单。
例如,String
类提供了多个重载方法indexOf(),可以查找子串:
int indexOf(int ch)
:根据字符的Unicode码查找;int indexOf(String str)
:根据字符串查找;int indexOf(int ch, int fromIndex)
:根据字符查找,但指定起始位置;int indexOf(String str, int fromIndex)
根据字符串查找,但指定起始位置。
例如
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); //3
System.out.println(n2); //2
System.out.println(n3); //5
}
}
例:输入时分秒以24或12小时制输出
import java.text.DecimalFormat;
public class Time2 extends Object {
private int hour; // 0 - 23
private int minute; // 0 - 59
private int second; // 0 - 59
public void setTime(int h){
setTime(h,0,0);
}
public void setTime(int h,int m){
setTime(h,m,0);
}
public void setTime( int h, int m, int s ){
setHour( h );
setMinute( m );
setSecond( s );
}
public void setHour( int h ){ //setHour方法
this.hour = ( ( h >= 0 && h < 24 ) ? h : 0 );
}
public void setMinute( int m ){ //setMinute方法
minute = ( ( m >= 0 && m < 60 ) ? m : 0 );
}
public void setSecond( int s ){ //setSecond方法
second = ( ( s >= 0 && s < 60 ) ? s : 0 );
}
public int getHour(){ //getHour方法
return this.hour;
}
public int getMinute(){ //getMinute方法
return minute;
}
public int getSecond(){ // getSecond方法
return second;
}
public String toUniversalString(){
DecimalFormat twoDigits = new DecimalFormat( "00" );
return twoDigits.format( hour ) + ":" +
twoDigits.format( minute ) + ":" + twoDigits.format( second );
}
public String toStandardString(){
DecimalFormat twoDigits = new DecimalFormat( "00" );
return ( (hour == 12 || hour == 0) ? 12 : hour % 12 ) + ":" +
twoDigits.format( minute ) + ":" + twoDigits.format( second ) +
( hour < 12 ? " AM" : " PM" );
}
}
public class TimeTest2 {
public static void main( String args[] ){
Time2 time = new Time2();
String output = "The initial universal time is: " +
time.toUniversalString() + "\nThe initial standard time is: " +
time.toStandardString();
time.setTime( 11);
output += "\n\nUniversal time after setTime is: " +
time.toUniversalString() +
"\nStandard time after setTime is: " + time.toStandardString();
time.setTime( 11,10);
output += "\n\nUniversal time after setTime is: " +
time.toUniversalString() +
"\nStandard time after setTime is: " + time.toStandardString();
time.setTime( 11,10,5);
output += "\n\nUniversal time after setTime is: " +
time.toUniversalString() +
"\nStandard time after setTime is: " + time.toStandardString();
System.out.println(output);
}
}