Computer Applications
What is the use of the keyword this?
Java Constructors
6 Likes
Answer
Within a constructor or a method, this is a reference to the current object — the object whose constructor or method is being invoked. The keyword this stores the address of the currently-calling object.
For example, the below program makes use of the this keyword to resolve the conflict between method parameters and instance variables.
class Area
{
int length, breadth;
public Area(int length, int breadth) {
this.length = length;
this.breadth = breadth;
}
public void Display() {
int area = length * breadth;
System.out.println("Area is " + area);
}
public static void main(String args[J) {
Area area = new Area(2, 3);
area.Display();
}
}
Answered By
3 Likes
Related Questions
If a class is named DemoClass, what names are allowed as constructor names in the class DemoClass?
Explain the concept of constructor overloading with an example.
What is a no-argument constructor? Does every class have a no-argument constructor?
Create a class named Pizza that stores details about a pizza. It should contain the following:
Instance Variables:
String pizzaSize — to store the size of the pizza (small, medium, or large)
int cheese — the number of cheese toppings
int pepperoni — the number of pepperoni toppings
int mushroom — the number of mushroom toppingsMember Methods:
Constructor — to initialise all the instance variables
CalculateCost() — A public method that returns a double value, that is, the cost of the pizza.
Pizza cost is calculated as follows:- Small: Rs.500 + Rs.25 per topping
- Medium: Rs.650 + Rs.25 per topping
- Large: Rs.800 + Rs.25 per topping
PizzaDescription() — A public method that returns a String containing the pizza size, quantity of each topping, and the pizza cost as calculated by CalculateCost().