The this Keyword
Part of the Object Oriented Programming section of Coddy's Java journey — lesson 4 of 87.
The this keyword refers to the current instance of a class. It distinguishes between fields and parameters with the same name.
Without this, the parameter shadows the field
public class Person {
private String name;
public Person(String name) {
name = name; // Assigns parameter to itself!
}
}Using this to correctly assign values
public class Person {
private String name;
public Person(String name) {
this.name = name; // Assigns parameter to field
}
public String getName() {
return this.name;
}
}Using this in methods
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getDescription() {
return this.name + " is " + this.age + " years old";
}
}The this keyword always points to the current object. It's essential when parameter names match field names, preventing confusion and bugs.
Challenge
MediumComplete the Person class using the this keyword to distinguish between fields and parameters:
- A constructor that uses
thisto assign parameters to fields - Getter methods using
thisto access fields - A
getDescription()method returning"<name>, age <age>, from <city>"
Cheat sheet
The this keyword refers to the current instance of a class and distinguishes between fields and parameters with the same name.
Without this, the parameter shadows the field:
public Person(String name) {
name = name; // Assigns parameter to itself!
}Using this to correctly assign values:
public Person(String name) {
this.name = name; // Assigns parameter to field
}Using this in getter methods:
public String getName() {
return this.name;
}Using this with multiple fields:
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getDescription() {
return this.name + " is " + this.age + " years old";
}
}Try it yourself
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String name = scanner.nextLine();
int age = Integer.parseInt(scanner.nextLine());
String city = scanner.nextLine();
Person person = new Person(name, age, city);
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
System.out.println("City: " + person.getCity());
System.out.println(person.getDescription());
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe this KeywordMethodsFields (Attributes)Constructor MethodConstructor OverloadingRecap - Simple Calculator4Inheritance
Basic Inheritance (extends)The super KeywordMethod Overriding (@Override)Constructor ChainingThe Object ClassSingle & Multilevel InheritWhy No Multi Class InheritRecap - Employee Hierarchy7Special Methods & Object Class
toString() Methodequals() and hashCode()clone() MethodcompareTo() and ComparableComparator InterfaceRecap - Custom Sorting2Access Modifiers & Encapsulate
Access Levels OverviewGetter and Setter MethodsInformation HidingThe final KeywordRecap - Bank Account Manager5Polymorphism
Method Overloading BasicsMethod Overriding (Run-Time)Upcasting and DowncastingThe instanceof OperatorAbstract Classes and MethodsRecap - Shape Calculator8Advanced OOP Concepts
Composition vs InheritanceAggregation vs CompositionInner Nested & Anonymous ClassEnums and Enum MethodsRecords (Java 16+)Sealed Classes (Java 17+)3Class Props & Static Member
Instance vs Static VariablesStatic MethodsStatic BlocksConstants (static final)Recap - Counter & Utility6Interfaces & Abstract Classes
Introduction to InterfacesImplementing InterfacesMulti Interface ImplemenDefault & Static in InterfaceAbstract Classes vs InterfacesFunctional InterfacesRecap - Payment System