[英]No-argument constructor calling 2-argument constructor
I am trying to call to make a 2-arg constructor the default constructor. 我试图调用使2-arg构造函数成为默认构造函数。 By this I mean; 我的意思是这个; when the no-arg constructor is called, it calls the 2-arg constructor with default values. 当调用no-arg构造函数时,它使用默认值调用2-arg构造函数。
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;
}
}
How do I call the 2nd constructor? 我如何调用第二个构造函数?
Just write 写吧
public Foo()
{
this(0, 0);
}
Note that it has to be the very first thing in the constructor. 请注意,它必须是构造函数中的第一件事。
(This is specified in §8.8.7.1 "Explicit Constructor Invocations" of The Java Language Specification, Java SE 8 Edition , which also specifies how to invoke a specific superclass constructor.) (这在Java语言规范Java SE 8 Edition的 §8.8.7.1“显式构造函数调用”中指定,它还指定了如何调用特定的超类构造函数。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.