Java中构造函数重载和方法重载

来源:互联网 发布:ps mac 破解版 编辑:程序博客网 时间:2024/04/30 03:59

源码

class Tree {int height;Tree() {prt("Planting a seeding");height = 0;}Tree(int i) {prt("Creating new Tree that is " + i + " feet tall");height = i;}void info() {prt("Tree is " + height + " feet tall");}void info(String s) {prt(s + " : Tree is " + height + " feet tall");}private void prt(String s) {System.out.println(s);}}public class Overloading {public static void main(String[] args) {for (int i = 0; i < 2; i++) {Tree t = new Tree(i);// Overloaded methodt.info();t.info("overloaded method");}// Overloaded constructornew Tree();new Tree(2);}}

运行结果


构造函数重载:

Tree 既可创建成一颗种子,不含任何自变量;亦可创建成生长在苗圃中的植物。为支持这种创建,共使用了
两个构造函数,一个没有自变量(默认构造函数),另一个采用现
成的高度。

方法重载:
我们也有可能希望通过多种途径调用info()方法。例如,假设我们有一条额外的消息想显示出来,就使用
String 自变量;而假设没有其他话可说,就不使用。由于为显然相同的概念赋予了两个独立的名字,所以看
起来可能有些古怪。幸运的是,方法过载允许我们为两者使用相同的名字。

0 0