Why isn't the "this" keyword necessary in constructors while it is in regular methods? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why isn't the "this" keyword necessary in constructors while it is in regular methods?

24th Mar 2023, 2:59 PM
AlexFr
AlexFr - avatar
2 Answers
+ 7
If it is unambiguous that the name refers to the property, we can leave it out. If the parameter name in the constructor happens to have the same name as the property, it is ambiguous and the compiler "assumes" you mean the parameter name. Have a look at the 1st example here: https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html
24th Mar 2023, 3:10 PM
Lisa
Lisa - avatar
+ 3
Lisa Also I guess it applies because the exact role of the constructor is to have access to the instant variables by default and it makes sense 🤔 Thank you
24th Mar 2023, 3:48 PM
AlexFr
AlexFr - avatar