5.2 方法重载
导航
- 重载(overload):相同的此何以表达不同的含义
- 方法重载:让方法名相同而形参不同的构造器同时存在,同时尽管方法重载是构造器所必须的,但它亦可用于其他方法,而且用法同样方便
//:initialization/Overloading.java
//Demonstration of both constructor
//and ordinary method overloading
class Tree{
int height;
Tree(){
System.out.println("Planting a seeding");
height=0;
}
Tree(int initialHeight){
height=initialHeight;
System.out.println("Creating new Tree that is "+height+" feet tall");
}
void info(){
System.out.println("Tree is "+ height + " feet tall");
}
void info(String s){
System.out.println(s+" :Tree is "+height+" feet tall");
}
}
public class Overloading{
public static void main(String[] args){
for(int i=0;i<5;i++){
Tree t=new Tree(i);
t.info();
t.info("overloaded method");
}
new Tree();//Overloaded constructor
}
}/*output:
overloaded method :Tree is 0 feet tall
Creating new Tree that is 1 feet tall
Tree is 1 feet tall
overloaded method :Tree is 1 feet tall
Creating new Tree that is 2 feet tall
Tree is 2 feet tall
overloaded method :Tree is 2 feet tall
Creating new Tree that is 3 feet tall
Tree is 3 feet tall
overloaded method :Tree is 3 feet tall
Creating new Tree that is 4 feet tall
Tree is 4 feet tall
overloaded method :Tree is 4 feet tall
Planting a seeding
*///:~
5.2.1 区分重载方法
- 每个重载方法都必须有一个独一无二的参数列表
-
甚至参数顺序的不同也可以区分两个方法,但是这样会使代码难以维护
//:initialization/OverloadingOrder.java //Overloading based on the order of the arguments public class OverloadingOrder{ static void f(String s,int i){ System.out.println("String: "+s+" ,int: "+i); } static void f(int i,String s){ System.out.println("int: "+i+"String: "+s); } public static void main(String[] args){ f("String first",11); f(99,"Integer first"); } }/*output: String: String first ,int: 11 int: 99String: Integer first *///:~
-
5.2.2 涉及基本类型的重载
- 如果传入的数据类型小于方法中声明的形参类型,实际数据类型就会被提升
- 如果传入的实际参数大于重载方法声明的形参,就得通过类型转换来进行窄化处理
5.2.3 以返回值区分重载方法
- 行不通