Actually, we have many confusion about the work of this in Java.. One day, I used to think, people are afraid of this thing..So, I should make something to make this proud..😂😂
(this) is a reference variable. This is used in many situations...
So, it's time to see the usages of this in java.....
1.It can be used to refer instance variable of current class.
2. It can be used to invoke or initiate current class constructor.
3. It can be passed as an argument in the method call.
4. It can be passed as argument in the constructor call
let's talk about an example:
class Book
{
string name;
string book_id;
public void setter(string n,string id)
{
name=name;
book_id=id;
}
//it can be written by this //
public void setter(string n,string id)
{
this.name=name;
this.book_id=id;
}
public static void main(string args[])
{
Book b1 = new Book();
}
Now the thing we can do is:
public void setter(string n,string id)
{
b1.name=name;//this can be replaced by object ..//
b1.book_id=id;
}
public static void main(string args[])
{
Book b1 = new Book(); //A new object is created ... //
}
So, we can say from the discussion that
Keyword THIS is a reference variable in Java that refers to the current object.
(this) is a reference variable. This is used in many situations...
So, it's time to see the usages of this in java.....
Let's Start::::-----
1.It can be used to refer instance variable of current class.
2. It can be used to invoke or initiate current class constructor.
3. It can be passed as an argument in the method call.
4. It can be passed as argument in the constructor call
let's talk about an example:
class Book
{
string name;
string book_id;
public void setter(string n,string id)
{
name=name;
book_id=id;
}
//it can be written by this //
public void setter(string n,string id)
{
this.name=name;
this.book_id=id;
}
public static void main(string args[])
{
Book b1 = new Book();
}
Now the thing we can do is:
public void setter(string n,string id)
{
b1.name=name;//this can be replaced by object ..//
b1.book_id=id;
}
public static void main(string args[])
{
Book b1 = new Book(); //A new object is created ... //
}
So, we can say from the discussion that
Keyword THIS is a reference variable in Java that refers to the current object.
Comments
Post a Comment