Java?方法的重載與參數(shù)傳遞詳解
方法重載概述
方法重載指同一個類中定義的多個方法之間的關系,滿足下列條件的多個方法互相構成重載
* 多個方法在同一個類中
* 多個放方法具有相同方法名
* 多個方法的參數(shù)不相同,類型不同或數(shù)量不同
方法重載特特點
* 重載僅對應方法的定義,與方法的調用無關,調用方法參照標準格式
* 重載僅針對同一個類中方法的名稱與參數(shù)進行識別,與返回值無關,換句話說不能通過返回值來判斷兩個方法是否構成重載
示例:
public class MethodDemo{
public static float fn(int a){
//方法體
}
public static int fn(int a,int b){
//方法體
}
}方法重載練習
需求:使用方法重載的思想,設計比較兩個整數(shù)是否相同的方法,兼容全整數(shù)類型(byte,short,int,long)
思路:
1.定義比較兩個數(shù)字的是否相同的方法compare()方法,參數(shù)選擇兩個int型參數(shù)
public static boolean compare(int a,int b){
return a==b;
}2.定義對應的重載方法,變更對應的參數(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. 完成方法調用,運行測試結果
public static void main(String args[ ]){
system.out.println(cpmpare(10,20));
}示例代碼:
public class hmm081 {
public static void main(String[] args) {
//調用方法
System.out.println(compare(10,20));
//強轉
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()內的number改變,但main()參數(shù)不變,不影響實際參數(shù)值,所以第二次輸出結果還是100
方法參數(shù)傳遞(引用類型)
對于引用類型的參數(shù),形式參數(shù)的改變,影響實際參數(shù)的值,如數(shù)組。


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

