Use app×
Join Bloom Tuition
One on One Online Tuition
JEE MAIN 2026 Crash Course
NEET 2026 Crash Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
175 views
in JAVA by (178k points)
edited by
What is the purpose of the this keyword in a constructor in Java?

Please log in or register to answer this question.

1 Answer

0 votes
by (178k points)

In Java, the this keyword is used to refer to the current object instance. In a constructor, the this keyword is used to differentiate between the member variables of a class and the parameters of the constructor that have the same name.

For example, consider the following class:

public class MyClass {
   int num;
   String str;

   public MyClass(int num, String str) {
      this.num = num;
      this.str = str;
   }
}
 

In the above example, the MyClass class has a parameterized constructor that takes two parameters, an integer num and a string str. The constructor initializes the member variables num and str with the values passed to it using the this keyword to refer to the current object instance.

By using this.num and this.str, we are explicitly stating that we want to set the values of the member variables of the current object instance to the values of the parameters passed to the constructor.

The this keyword is particularly useful in constructors when the parameter names are the same as the member variable names. It helps to avoid confusion and ensures that the member variables are properly initialized.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
2 answers

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...