The `this` keyword
Contents
In objected oriented (OO) design, objects are aware of the contents inside of themselves.
In Java, the object can access its attributes with the this keyword.
In Python, we commonly use the self variable (though it is arbitrary and up to you).
| |
In this example, we can see that we are using the this keyword to access the someNumber attribute in our object.
Removing this this keyword
Sometimes we can also get rid of the this keyword, as the Java language does not explicitly require it.
| |
When this is required
There are times when we must use the this keyword, however.
For example, when we have arguments in the function signature.
| |
We cannot use this in the context of a class method (In Java, these would be static methods)
Summary
- As good practice, always use the
thiskeyword when an attribute is accessed. thiswill not work instatic/ class methods