JAVA是可以實(shí)現(xiàn)方法重載的,所謂方法重載,就是在同一個(gè)類中有兩個(gè)以上相同方法名但是參數(shù)列表不同的方法,叫做方法重載.方法重載與返回值和返回類型無關(guān),只與參數(shù)名和參數(shù)列表有關(guān).所以只要滿足以下幾點(diǎn)就是方法重載:
- 方法名必須相同
- 方法參數(shù)列表必須不同,包括參數(shù)個(gè)數(shù)和參數(shù)類型.
????a. 如果參數(shù)個(gè)數(shù)不同,就不管參數(shù)類型
????b. 如果參數(shù)個(gè)數(shù)相同, 參數(shù)類型必須不同 - 方法的返回類型,修飾符可以相同也可以不同
其實(shí)在JAVA的API中,已經(jīng)大量使用到了方法的重載,比如說在開發(fā)過程中經(jīng)常使用到的系統(tǒng)輸出語句,就是方法重載,主要區(qū)別就是在參數(shù):
System.out.println("根據(jù)傳進(jìn)來的參數(shù)類型來調(diào)用對(duì)應(yīng)的輸出方法");
類的構(gòu)造方法,也是方法重載,因?yàn)闃?gòu)造方法分為有參和無參構(gòu)造方法:
public class overload {
public overload(){
super();
//無參的構(gòu)造方法;
}
public overload(String content){
super();
//有參的構(gòu)造方法;
}
}
方法重載實(shí)例
public class Test {
public static void main( String[] args){
overloadTest test = new overloadTest();
test.printMethod("我是一個(gè)接收一個(gè)字符串參數(shù)的方法");
test.printMethod(2);
test.printMethod("小明", 6);
overloadTest test1 = new overloadTest("我是有參構(gòu)造方法");
String str = test1.printMethod("哈哈哈", "嘻嘻嘻");
System.out.println(""+str);
}
}
class overloadTest{
/*
* JAVA API中使用了大量的方法重載
* 比如: 1) 系統(tǒng)輸出 System.out.println("根據(jù)傳入的參數(shù)類型找到對(duì)應(yīng)的方法");
* 2) 類的構(gòu)造方法:分為有參和無參的構(gòu)造方法 ps:構(gòu)造方法是沒有返回值的
*/
public overloadTest() {
super();
// TODO Auto-generated constructor stub
System.out.println("無參構(gòu)造方法");
}
public overloadTest(String content) {
super();
System.out.println(""+content);
}
/*
* 方法重載:在同一個(gè)類中有多個(gè)相同方法名但是參數(shù)列表不同的叫做方法重載,方法重載與返回值無關(guān)
* 只與方法名和參數(shù)列表有關(guān).
* 1) 方法名要相同.
* 2) 方法參數(shù)列表必須不同,包括參數(shù)個(gè)數(shù)和參數(shù)類型,以此區(qū)分不同的方法體
* a 如果參數(shù)個(gè)數(shù)不同,就不需要看參數(shù)類型了
* b 如果參數(shù)個(gè)數(shù)相同,那么參數(shù)類型必須不同
* 3) 方法的返回類型,修飾符可以相同也可以不同
* */
public void printMethod(String content){
System.out.println("輸出一個(gè)字符串:"+content);
}
public void printMethod(int number){
System.out.println("輸出一個(gè)整型數(shù)字:"+number);
}
public void printMethod(String name, int age){
System.out.println(""+name+"今年"+age+"歲了");
}
public String printMethod(String str1, String str2){
return str1+str2;
}
}