我遇到了这段代码,上面写着
new Class_Name(); // (i)
现在,通常我会看到分配给变量的新语句的结果:
Class_Name n = new Class_Name();
并n
引用创建的对象。调用 (i) 时真正发生了什么?为什么会有人想要这样做?它有什么用途?
代码
class Tree {
int height;
Tree() {
print("Planting a seedling");
height = 0;
}
Tree(int initialHeight) {
height = initialHeight;
print("Creating new Tree that is " +
height + " feet tall");
}
void info() {
print("Tree is " + height + " feet tall");
}
void info(String s) {
print(s + ": Tree is " + height + " feet tall");
}
}
enter code here
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");
}
// Overloaded constructor:
new Tree();
}
}