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.

  1. Class OrderPizza:

    • Instance Variables:
      • pname (pizza name): A String to store the name of the pizza.
      • quantity: An int to store the number of pizzas ordered.
      • cost: A double to store the total cost of the order.
    • Constructor:
      • The constructor takes three parameters: pname, quantity, and cost.
      • The this keyword 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.
    • Method show():
      • Displays the pizza name, quantity, and bill amount. The this keyword is used explicitly to refer to the instance variables.
  2. Class ThisPizzaDemo:

    • Contains the main() method, which is the entry point of the program.
    • Creates an object of the OrderPizza class and passes the pizza name, quantity, and cost to its constructor.
  3. this Keyword:

    • The this keyword 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.

Output

Pizza Name: Cheeze Burst
Quantity: 2
Bill Amount: 450.0