Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 844
Asher Garland Avatar asked Nov 30 '22 15:11

Asher Garland


1 Answers

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

like image 151
ruakh Avatar answered Dec 09 '22 08:12

ruakh