0

Local vs instance variable

Can a same name variable be instance and local ?

17th Apr 2020, 7:28 PM
Sagar Gupta
Sagar Gupta - avatar
2 odpowiedzi
+ 4
Just adding to what Denise Roßberg has mentioned in his answer. It is possible to have same name for both instance and local variables because local variables have a block level scope. They can be accessed only within the block { } in which they are defined. On the other hand, instance variables have a class level scope and can be accessed anywhere within the class. One doesn't know about the other.
17th Apr 2020, 9:09 PM
Avinesh
Avinesh - avatar
+ 2
Yes. To avoid conflicts you need to use the keyword this. For example you have an instance variable int number and also a local variable int number. If you mean the local variable you can write number. And if you mean your instance variable you have to write this.number.
17th Apr 2020, 7:58 PM
Denise Roßberg
Denise Roßberg - avatar