sometimes the tasks could be met by typing Cat.fullName = fullName, sometimes this.fullName = fullName
what is the difference?
plus to non-programmers, level 4 concerning the visibility is suddenly very tough, even if we try to gather additional information online
Cat.fullName = fullName v.s. this.fullName = fullName
Under discussion
Comments (4)
- Popular
- New
- Old
You must be signed in to leave a comment
Guadalupe Gagnon
13 November 2020, 14:54useful
A lot of this has to do with variable scope, and what follows applies ONLY when you are coding in the actual class.
You can use the keyword 'this' to call all class variables when you want, however the ONLY time it is absolutely required is when you have a local variable with a duplicate name. Otherwise you can just call the variable name without 'this' with no problem.
The proper way to call static variables is with the class name (that contains the static variable) such as with Cat.staticVariableName, however you can use 'this' to call static variables without a problem
With non-static variables you can't call them using the class name as you can with static variables, you must use the 'this' keyword (but only when a naming conflict exists). So:
and if the constructor looked like this instead:
+7
Guadalupe Gagnon
13 November 2020, 15:01useful
Variable scope isn't too hard. When a variable is declared it can be seen within the block of code it is declared in, and every block of code within that block. So:
At line 13, where the double x is declared in the while loop, all the variables can be seen in used.
At line 10, where the int i is declared in the for loop: var1, var2, and i can all be seen and used
At Line 7, where String var2 is declared, var1 and var2 can be seen and used
At line 3, where String var1 is decalred, only var1 can be seen and used +7
Albert
16 November 2020, 03:09
Thanks for the clear & concise explanation, I am less confused right now : )
0
Guadalupe Gagnon
16 November 2020, 14:22useful
It just takes time and practice. Everyone, including myself, all get a little confused when learning this for the first time. Remember these rules:
- variables are only visible to the code within the block they are declared in, and all inner blocks within that block. Properly indented code helps immensely in identifying at a glance which block of code a particular variable is declared in.
- when there is a name conflict between local variables (those within a method) and class fields (the variables declared in the class block), then you will need to use the keyword 'this' (or the 'class name' if the variable is static)
Remembering these rules will help when you start learning about advanced concepts like access modifiers, pointer aliasing, and synchronization. These will be introduced in later levels, so no need to stop and try to learn these now.
+8