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