方法的重载是指在一个类中可以有名字相同的多个方法,但这些方法的参数必须相同,或者是参数个数不同,或者是参数类型不同。返回值可以相同,也可以不同。重载的价值在于它允许通过使用一个方法名来访问多个方法。
例子:
package com.zhm.demo;
/**
*
* @author zhm
* 声明重载demo类
*
*/
public class MethodOverloading {
//声明方法
public static void receive(int i){
System.out.println("Receive one int Parameter.");
System.out.println("\ni="+i);
}
//方法重载
public static void receive(double d){
System.out.print("Receive one double Parameter.");
System.out.println("\nd="+d);
}
public static void receive(String c){
System.out.println("Receive one String parameter.");
System.out.print("\nc="+c);
}
public static void receive(int i,int j){
System.out.println("Receive two int parameter.");
System.out.println("\ni+j="+(i+j));
}
public static void receive(int i,double j){
System.out.println("Receive two parameter");
System.out.println("\ni+j="+(i+j));
}
public static void main(String[] args) {
receive(10);
receive(10.0);
receive("10.0");
receive(10+10);
receive(10+10.0);
}
}
结果:
Receive one int Parameter.
i=10
Receive one double Parameter.
d=10.0
Receive one String parameter.
c=10.0
Receive one int Parameter.
i=20
Receive one double Parameter.
d=20.0