0

I learned two things:

  1. The new-operator creates a new instance and then the stated connstructor is executed to initialise that new instance
  2. A constructor call (this()) creates a new instance.

For my understanding these statements object each other.

For example wouldn't new Example() create two instances then, because the new-operator creates one and the constructor calls this() and creates another? Of course it doesn't but what exactly creates an instance now...?

class Example
{
    private boolean _b;

    public Example()
    {
        this(false);
    }

    public Beispiel(boolean b)
    {
        _b = b;
    } 
}
Lester
  • 1,820
  • 1
  • 26
  • 43

3 Answers3

6

Your second point is incorrect: Invoking this() doesn't "create a new instance". Rather, it calls a (usually different) constructor than the one called by new.

Calling new is what creates the new instance.

Bohemian
  • 389,931
  • 88
  • 552
  • 692
0

You can use this inside a constructor to call constructors of the same class with different number of arguments for example:

class Example{
    private boolean b;
    public Example(){
        this(false) // you now call public Example(boolean b) to save code istead of    this.b=false
    }
    public Example(boolean b){
        this.b = b;
    }
}
nikolap
  • 99
  • 1
  • 7
0

By calling this(false) you do not create a new instance. You just call a constructor within a constructor(the one matching the number of the arguments you are passing), for which i cannot think of any efficient practical use right now, but nevertheless is perfectly valid. Note that, to chain constructors like that, you have to make a new constructor call in the first line of the "parent" constructor.If that makes sense. Bottomline; you create one object. Maybe adding print statements for each different constructor call can help you grasp this thing better.

Also, take a look here: How do I call one constructor from another in Java?

Community
  • 1
  • 1
gkrls
  • 2,568
  • 2
  • 13
  • 29