"this" in Java

Overview


Java uses the keyword "this". Object languages tend to use "this" or "self".

What "this" means is the object/class you are coding in.

Let's look at an example.

"this" -> "me/myself/I" 🙋🏽

"this" means the current object we are coding in.

  • Student
  • Coding in "Student", "this" is Student.
  • Planet
  • Coding in "Planet", "this" is Planet
public class 
1
Student { private String firstName; private String lastName; private int credits; public void foo() {
2
CODING HERE } } //end Student public class
3
Planet { String name; int radius; //miles public void foo() {
4
CODING HERE } }
  • We are coding in Person. Thus, "this" is "Person"
  • Person" has ivar "firstName
  • Accessing Person's ivar "firstName" using "this"

NOTE WELL -- Learn little by little... 👍🏽
public class 
1
Person { private String
2
firstName; private String lastName; public Person(String aFirstName, String aLastName) {
3
this.firstName = aFirstName; this.lastName = aLastName; }
  • We are coding in Person. Thus, "this" is "Person"
  • Person" has instance method "getFullName
  • Accessing Person's method "getFullName" using "this"
public class 
1
Person { private String firstName; private String lastName; public Person(String aFirstName, String aLastName) { this.firstName = aFirstName; this.lastName = aLastName; } public void setNames(String aFirstName, String aLastName) { this.firstName = aFirstName; this.lastName = aFirstName; } public String
2
getFullName()
{ String fullName; fullName = this.firstName + " " + lastName; return fullName; } public String toString() { return "Person: " +
3
this.getFullName(); } }