“5.2 方法重载”这一小节一上来讲了一个取名字的问题,放在计算机编程语言里面,就是相同的名字的方法或者函数可以表达多种不同的含义,他们被“重载”了。下面直接举一个包含构造器重载和普通方法重载的例子,更直观的对“重载”有个理解:
importstaticnet.mindview.util.Print.*; classTree { intheight; Tree() { print("Planting a seedling"); height=0; } Tree(intinitialHeight) { height=initialHeight; print("Creating new Tree that is "+height+" feet tall"); } voidinfo() { print("Tree is "+height+" feet tall"); } voidinfo(Strings) { print(s+": Tree is "+height+" feet tall"); } } publicclassOverloading { publicstaticvoidmain(String[] args) { for(inti=0; i<5; i++) { Treet=newTree(i); t.info(); t.info("overloaded method"); } // Overloaded constructor: newTree(); } }
/* Output:
Creating new Tree that is 0 feet tall
Tree is 0 feet tall
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 seedling
*///:~
创建Tree对象时,即可以不含参数,也可以用树的高度当参数。对于普通的方法也是一样的道理,info()是不显示额外的信息,inf(String)则可以显示额外的信息。你还可以定义更多的重载函数,比如info(String,String)等等。从这些直观的代码可以总结出一个规律:相同名字的方法,每个重载的方法都必须有独一无二参数类型列表。从这个规律大家是不是就明白了什么是重载,不用过多的去追求文字上的定义描述了。
下面提到了一种情况就是,虽然参数顺序的不同也足以区分两个方法,不过,一般不建议这么做,因为这么做没什么意义,更增加了代码的维护难度:
importstaticnet.mindview.util.Print.*; publicclassOverloadingOrder { staticvoidf(Strings, inti) { print("String: "+s+", int: "+i); } staticvoidf(inti, Strings) { print("int: "+i+", String: "+s); } publicstaticvoidmain(String[] args) { f("String first", 11); f(99, "Int first"); } }
/* Output:
String: String first, int: 11
int: 99, String: Int first
*///:~