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,830
  • 1
  • 27
  • 44

4 Answers4

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
  • 412,405
  • 93
  • 575
  • 722
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

No. Invoking this doesn't create a new instance. Only invoking new creates a new instance of the object.

Your syntax this(argument) is explicit invocation of a different constructor within the same class.

Such invocation can be done , for instance, to initialize some variables in the object.

See from the Oracle Java tutorials Using the this keyword

paisanco
  • 4,098
  • 6
  • 27
  • 33
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,618
  • 2
  • 15
  • 29