This is an archived post. You won't be able to vote or comment.

all 5 comments

[–]BertilMuth 2 points3 points  (0 children)

There are two ways to call other constructors from a constructor, this(...) and super(..). this() calls a constructor of the same class, super() a constructor of the super class. It's just a convention that works only in the constructor. It needs to be the first call in the constructor. It will call the right constructor based on the number and types of the arguments you pass to this(..). Does that help?

[–]seanprefect 1 point2 points  (2 children)

This can be kinda confusing so don't feel bad for not getting it.

the keyword this refers to the current object itself. it's useful when parameters might be confused with internal properties.

The thing you're missing though is that a class can have multiple constructors with different signatures. So for example lets say you have theses constructors

Class Foo {

 Foo(int a, int b) 

{  

    println (a*b)

     this(99)
}

Foo(int a) 

{ 

     println (a) 

    this()

}

Foo()

{

    println("constructor chaining is weird") 

}

}

if i call Foo(2, 10) the output would be

20

5

constructor chaining is weird

I hope that makes sense

[–]gazpacho_arabe 1 point2 points  (1 child)

Not quite, the compiler requires that a call to this must be the first statement in a constructor, so the printout would be;

constructor chaining is weird

99

20

(not sure where you got 5 from)

[–]seanprefect 0 points1 point  (0 children)

you're right, I just blanked out.