18_方法重載

第十八章 方法重載

作者:張子默

一、方法重載

方法重載是指在同一個類中允許存在一個以上的同名方法,只要它們的參數列表不同即可,與修飾符和返回值類型無關。

  • 參數列表:個數不同,數據類型不同,順序不同

  • 重載方法調用:JVM通過方法的參數列表調用不同的方法

二、實例

	/*
	問題:對於功能類似的方法來說,因爲參數列表不一樣,卻需要記住那麼多不同的方法名稱,太麻煩。
	
	方法的重載(Overload),多個方法名稱一樣,但是參數列表不一樣。
	
	好處:只需要記住唯一一個方法名稱,就可以實現類似的多個功能。
	
	方法重載與下列因素相關:
		1.參數個數不同
		2.參數類型不同
		3.參數的多類型順序不同
		
	方法重載與下列因素無關:
		1.與參數的名稱無關
		2.與方法的返回值類型無關
	*/
	public class Demo09MethodOverload {
		public static void main(String[] args) {
			/*System.out.println(sumTwo(10, 20)); // 30
			System.out.println(sumThree(10, 20, 30)); // 60
			System.out.println(sumFour(10, 20, 30, 40)); // 100*/
			
			System.out.println(sum(10, 20)); // 兩個參數的方法
			System.out.println(sum(10, 20, 30)); // 三個參數的方法
			System.out.println(sum(10, 20, 40)); // 四個參數的方法
			//System.out.println(sum(10, 20, 40, 50)); // 找不到任何方法來匹配,所以錯誤!
		}
		
		public static int sum(int a, double b) {
			return (int) (a + b);
		}
		
		public static int sum(double a, int b) {
			return (int) (a + b);
		}
		
		public static int sum(int a, int b) {
			System.out.println("有2個參數的方法執行!");
			return a + b;
		} 
		
		//錯誤寫法!與參數名稱無關
		/*public static int sum(int x, int y) {
			return x + y;
		}*/
		
		//錯誤寫法!與方法的返回值類型無關
		/*public static double int sum(int a, int b) {
			return a + b;
		}*/
		
		public static int sum(double a, double b) {
			return (int) (a + b);
		}
		
		public static int sum(int a, int b, int c) {
			System.out.println("有3個參數的方法執行!");
			return a + b + c;
		}
		
		public static int sum(int a, int b, int c, int d) {
			System.out.println("有4個參數的方法執行!");
			return a + b + c + d;
		}
	
	}

三、練習

  • 比較兩個數據是否相等
		/*
		要求:比較兩個數據是否相等
			參數類型分別爲兩個byte類型、兩個short類型、兩個int類型、兩個long類型,並在main方法中進行測試
		*/
		public class Demo10MethodOverloadSame {
			public static void main(String[] args) {
				byte a = 10;
				byte b = 20;
				System.out.println(isSame(a, b));
				
				System.out.println(isSame((short) 20, (short) 20));
				
				System.out.println(isSame(11, 12));
				
				System.out.println(isSame(10L, 20L));
				
			}
			
			public static boolean isSame(byte a, byte b) {
				System.out.println("兩個byte參數的方法執行!");
				boolean same;
				if(a == b) {
					same = true;
				}else {
					same = false;
				}
				return same;
			}
			
			public static boolean isSame(short a, short b) {
				System.out.println("兩個short參數的方法執行!");
				boolean same = a==b?true:false;
				return same;
			}
			
			public static boolean isSame(int a, int b) {
				System.out.println("兩個int參數的方法執行!");
				return a==b;
			}
			
			public static boolean isSame(long a, long b) {
				System.out.println("兩個long參數的方法執行!");
				if(a==b) {
					return true;
				}else {
					return false;
				}
			}
		
		}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章