This keyword in
java:
- The this keyword
is used to refers the current object in a method or constructor.
- The most common
use of the this keyword is used to eliminate the confusion between the same
name of variables used in different methods (constructor parameter).
- Mainly used for
avoiding conflicts from methods or variables or passing parameters.
Example program
without using this keyword:
public class
Item_Details
{
String item_name;
int qty;
float price;
Item_Details(String x, float y, int z)
{
//Assigning parameters to global
variable
item_name=x;
price=y;
qty=z;
}
void display()
{
double amt=price*qty;
System.out.println("Item name\t
Unit price\t Qty \t Payment");
System.out.println(item_name +
"\t\t " + price + "\t\t " + qty+ "\t " +amt);
}
}
class
Without_this_keyword {
public static void main(String args[]) {
Item_Details obj1 = new
Item_Details("Pen",5,2);
obj1.display();
Item_Details obj2 = new
Item_Details("Eraser",2,3);
obj2.display();
}
}
Output:
Assigning same
parameter in global variable and it output become null:
public class
Item_Details
{
String item_name;
int qty;
float price;
Item_Details(String item_name, int qty, float
price)
{
//Assigning same parameter in global
variable
item_name=item_name;
price=price;
qty=qty;
}
void display()
{
double amt=price*qty;
System.out.println("Item name\t
Unit price\t Qty \t Payment");
System.out.println(item_name +
"\t\t " + price + "\t\t " + qty+ "\t " +amt);
}
}
class
Without_this_keyword {
public static void main(String args[]) {
Item_Details obj1 = new
Item_Details("Pen",5,2);
obj1.display();
Item_Details obj2 = new
Item_Details("Eraser",2,3);
obj2.display();
}
}
Output:
Using this
keyword:
Overcome above
problem for using this keyword.
Example program
with this keyword:
public class
Item_Details
{
String item_name;
int qty;
float price;
Item_Details(String item_name, int qty,
float price)
{
this.item_name=item_name;
this.qty =qty;
this.price=price;
}
void display()
{
double amt=price*qty;
System.out.println("Item name\t
Unit price\t Qty \t Payment");
System.out.println(item_name +
"\t\t " + price + "\t\t " + qty+ "\t " +amt);
}
}
class
With_this_keyword {
public static void main(String args[]) {
Item_Details obj1 = new Item_Details("Pen",5,2);
obj1.display();
Item_Details obj2 = new
Item_Details("Eraser",2,3);
obj2.display();
}
}
Output:
Another method to overcome above problem without using this keyword:
public class
Item_Details
{
String item_name;
int qty;
float price;
Item_Details(String item_name, int qty,
float price)
{
double amt=price*qty;
System.out.println("Item name\t
Unit price\t Qty \t Payment");
System.out.println(item_name +
"\t\t " + price + "\t\t " + qty+ "\t " +amt);
}
}
class
Without_this_keyword {
public static void main(String args[]) {
Item_Details obj1 = new
Item_Details("Pen",5,2);
Item_Details obj2 = new
Item_Details("Eraser",2,3);
}
}
Output:
No comments:
Post a Comment