1.premier mode d'utilisation
this
The keyword this in Java refers to the current class instance i.e object. It can be used in multiple ways,
e.g
class Square{
Square(int height, int width)
{
this.height = height;
this.width = width;
}
}
Here this keyword makes sure the parameters belongs to object and not parameters passed through constructor Square().
2.deuxième mode d'utilisation
this()
this keyword here basically points to the constructor of the class.
It can be used by one constructor to explicitly invoke another constructor in the same class.
e.g
class Square
{
int height;
int width;
Square()
{
this(0,0);
}
Square(int side)
{
this(side, side);
}
Square(int height, int width)
{
this.height = height;
this.width = width;
}
}
So here, if we pass no arguments to constructor, 0 is taken as both arguments and if only one argument is passed then same value is used for both height and width.
网友评论