无参数构造函数调用 2 个参数构造函数

发布于 2024-12-21 11:02:57 字数 333 浏览 1 评论 0原文

我试图调用使 2-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;
  }
}

如何调用第二个构造函数?

I am trying to call to make a 2-arg constructor the default constructor.
By this I mean; when the no-arg constructor is called, it calls the
2-arg constructor with default values.

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

哆兒滾 2024-12-28 11:02:57

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.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文