Unit 3 Day 16 This Keyword
Share
Unit 3: Class Creation
Day 16 PracticeMedium
Focus: Using this to reference instance variables
Today's Question
Which statement correctly uses the this keyword in a constructor?
class="apcs-keyword">public class Student {
class="apcs-keyword">private String name;
class="apcs-keyword">private int age;
class="apcs-keyword">public Student(String name, int age) {
class="apcs-comment">// Which line is correct?
}
}
When parameter names match instance variable names, you must use this.variableName to refer to the instance variable. Without this, you would be assigning the parameter to itself.
Key Concept
The this keyword refers to the current object and is used to distinguish instance variables from parameters with the same name.