Java?方法的重載與參數(shù)傳遞詳解
方法重載概述
方法重載指同一個類中定義的多個方法之間的關(guān)系,滿足下列條件的多個方法互相構(gòu)成重載
* 多個方法在同一個類中
* 多個放方法具有相同方法名
* 多個方法的參數(shù)不相同,類型不同或數(shù)量不同
方法重載特特點
* 重載僅對應(yīng)方法的定義,與方法的調(diào)用無關(guān),調(diào)用方法參照標準格式
* 重載僅針對同一個類中方法的名稱與參數(shù)進行識別,與返回值無關(guān),換句話說不能通過返回值來判斷兩個方法是否構(gòu)成重載
示例:
public class MethodDemo{
public static float fn(int a){
//方法體
}
public static int fn(int a,int b){
//方法體
}
}方法重載練習(xí)
需求:使用方法重載的思想,設(shè)計比較兩個整數(shù)是否相同的方法,兼容全整數(shù)類型(byte,short,int,long)
思路:
1.定義比較兩個數(shù)字的是否相同的方法compare()方法,參數(shù)選擇兩個int型參數(shù)
public static boolean compare(int a,int b){
return a==b;
}2.定義對應(yīng)的重載方法,變更對應(yīng)的參數(shù)類型,參數(shù)變更為兩個long型參數(shù)
public static boolean compare(long a,long b){
return a==b;
}3.定義所有重載方法,兩個byte類型與兩個short類型參數(shù)
public static boolean compare(byte a,byte b){
//代碼片段
}
public static boolean compare(short a,short b){
//代碼片段
}4. 完成方法調(diào)用,運行測試結(jié)果
public static void main(String args[ ]){
system.out.println(cpmpare(10,20));
}示例代碼:
public class hmm081 {
public static void main(String[] args) {
//調(diào)用方法
System.out.println(compare(10,20));
//強轉(zhuǎn)
System.out.println(compare((byte)10,(byte)20));
System.out.println(compare((long)10,(long)10));
}
public static boolean compare(int a,int b){
System.out.println("int");
return a==b;
}
public static boolean compare(long a,long b){
System.out.println("long");
return a==b;
}
public static boolean compare(byte a,byte b){
System.out.println("byte");
return a==b;
}
public static boolean compare(short a,short b){
System.out.println("short");
return a==b;
}
}方法參數(shù)傳遞
方法參數(shù)傳遞(基本類型)
對于基本數(shù)據(jù)類型參數(shù),形式參數(shù)的改變,不影響實際參數(shù)的值

雖然形參change()內(nèi)的number改變,但main()參數(shù)不變,不影響實際參數(shù)值,所以第二次輸出結(jié)果還是100
方法參數(shù)傳遞(引用類型)
對于引用類型的參數(shù),形式參數(shù)的改變,影響實際參數(shù)的值,如數(shù)組。


到此這篇關(guān)于Java 方法的重載與參數(shù)傳遞詳解的文章就介紹到這了,更多相關(guān)Java 方法重載內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java編程實現(xiàn)比對兩個文本文件并標記相同與不同之處的方法
這篇文章主要介紹了Java編程實現(xiàn)比對兩個文本文件并標記相同與不同之處的方法,涉及java針對文本文件的讀取、遍歷、判斷等相關(guān)操作技巧,需要的朋友可以參考下2017-10-10

