无参数构造函数调用2参数构造函数
问题描述:
我想调用2-arg构造函数作为默认构造函数。 通过这个我的意思是;当调用no-arg构造函数时,它会使用默认值调用 2-arg构造函数。无参数构造函数调用2参数构造函数
public class Foo
{
int foo1;
int foo2;
public Foo()
{
Foo(0, 0); //error //I also tried this.Foo(0,0);
}
public Foo(int one, int two)
{
this.foo1 = one;
this.foo2 = two;
}
}
如何调用第二个构造函数?
答
只要写
public Foo()
{
this(0, 0);
}
注意,它必须是在构造函数的第一件事。
(这在§8.8.7.1 "Explicit Constructor Invocations" of The Java Language Specification, Java SE 8 Edition规定,也规定了如何调用一个特定的超类的构造函数)。
这是*几乎*一个很大的问题(如果它包含的具体问题,“我怎么叫2号构造?“),但它缺少你描述的部分(也就是我的意思是复制/粘贴)发生错误的输出,无论哪种方式。 – 2011-12-15 19:45:57