0

Consider the following code:

    public Fingerprint(HashMap<String, Integer> measurements) {
        this();
        mMeasurements = measurements;
    }

   public Fingerprint(HashMap<String, Integer> measurements, String map) {
        this(measurements);
        mMap = map;
    }

    public Fingerprint(int id, String map, PointF location) {
        this();
        mLocation = location;
    }

    public Fingerprint(int id, String map, PointF location, HashMap<String, Integer> measurements) {
        this(id, map, location);
        mMeasurements = measurements;
    }

what is the purpose of this(); in this context? Since I have the idea that "this" refers to the fields of the current object. is it the same definition here?

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
user3170491
  • 33
  • 1
  • 5
  • `this()` calling the noarg constructor `Fingerprint()`. See question http://stackoverflow.com/questions/285177/how-do-i-call-one-constructor-from-another-in-java – Matyas Jan 07 '14 at 22:53
  • "This" doesn't refer to the fields of the current object, but the current object itself. In a ctor it calls the parameter-less ctor. – Dave Newton Jan 07 '14 at 22:54
  • There has to be a no-arg constructor otherwise the code will not compile... – assylias Jan 07 '14 at 23:37

1 Answers1

6

Calling this(); as if it were a method is the way to invoke another constructor from within a constructor. You are effectively calling Fingerprint().

Please see the Java Tutorial on the subject, section "Using this with a Constructor".

rgettman
  • 176,041
  • 30
  • 275
  • 357
  • so If I'm calling Fingerprint, I'm not calling another constructor right? is it the same constructor itself? – user3170491 Jan 07 '14 at 22:54
  • No, it's the no-arg ctor, as stated. – Dave Newton Jan 07 '14 at 22:55
  • You have code in `Fingerprint()` that you'd also like to call in `Fingerprint(HashMap measurements)`. You can call another constructor in this way, from the current constructor. This also avoids duplication of code in constructors. – rgettman Jan 07 '14 at 22:57
  • so imagine that I have something like this: public Fingerprint(HashMap measurements) { mMeasurements = measurements; } the field mMeasurements will never be updated without "this"? – user3170491 Jan 07 '14 at 22:59
  • No, it just makes the constructor `Fingerprint(HashMap measurements)` do everything that the `FingerPrint()` constructor does (if anything), plus you also have the assignment `mMeasurements = measurements;`. – rgettman Jan 07 '14 at 23:01
  • @user3170491 "this" refers to the current instance. "this.foo" refers to the foo property of the current instance. "foo" refers to the most local "foo" reference, which may be an instance property, but it could be hidden by a method parameter name, a local variable, etc. – Dave Newton Jan 07 '14 at 23:05