Java Program to show usage of this pointer using Order Pizza Program
Program
class OrderPizza
{
String pname;
int quantity;
double cost;
orderPizza(String pname, int quantity, double cost)
{
this.pname = pname;
this.quantity = quantity;
this.cost = cost;
show();
}
void show()
{
System.out.println("Pizza Name: " + this.pname);
System.out.println("Quantity: " + this.quantity);
System.out.println("Bill Amount: " + this.cost);
}
}
public class ThisPizzaDemo
{
public static void main(String[] args)
{
orderPizza m = new orderPizza("Cheeze Burst", 2, 450.00);
}
}
This program demonstrates the usage of the this keyword in Java to reference the current instance of the class.
-
Class
OrderPizza:- Instance Variables:
pname(pizza name): AStringto store the name of the pizza.quantity: Anintto store the number of pizzas ordered.cost: Adoubleto store the total cost of the order.
- Constructor:
- The constructor takes three parameters:
pname,quantity, andcost. - The
thiskeyword is used to differentiate the instance variables (this.pname,this.quantity,this.cost) from the constructor's parameters with the same names. - After setting the values, it calls the
show()method to display the order details.
- The constructor takes three parameters:
- Method
show():- Displays the pizza name, quantity, and bill amount. The
thiskeyword is used explicitly to refer to the instance variables.
- Displays the pizza name, quantity, and bill amount. The
- Instance Variables:
-
Class
ThisPizzaDemo:- Contains the
main()method, which is the entry point of the program. - Creates an object of the
OrderPizzaclass and passes the pizza name, quantity, and cost to its constructor.
- Contains the
-
thisKeyword:- The
thiskeyword refers to the current instance of the class. - It is used to resolve conflicts between instance variables and parameters with the same name.
- It can also be used to explicitly call methods of the current object or refer to the current object.
- The
Output
Pizza Name: Cheeze Burst
Quantity: 2
Bill Amount: 450.0