简体   繁体   中英

No-argument constructor calling 2-argument constructor

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM