Instance variable becomes invisible after local var is declared
When you declare a local variable with开发者_C百科in method using the same name and type like instance variable of - does it mean the instance variable becomes 'invisible' inside that method?
public class Test {
Card card;
public void foo(){
Card card = new Card();
card.test();
}
}
So I'm declaring and instantiating local variable card in foo() method. And then test() method is called for local variable. If I removed the Card card = new Card();
test() method is invoked for instance variable.
What you are seeing is sometimes referred to as "shadowing" the variable. Any time a variable is declared within an inner scope, the variable becomes the default variable tied to that name until it goes out of scope.
In this case, you could access the class variable using syntax:
this.card
The instance variable doesn't become invisible, but it is hidden by the local variable. You can still access the it with this.card
.
You can access the instance variable using this.card
.
The this.variable
reference will always get you the instance variable. This can become useful if you have an argument to a function which is the same as an instance variable, though I would recommend trying to avoid the problem altogether if you can.
Yes, the locally scoped card will take precedence. You can use 'this' to reference the instance variable:
public void foo() {
Card card = new Card();
this.card.test(); // tests the instance variable card
card.test(); // tests the local card
}
Locally scoped variables in a method will take precedence over instance variables with the same name, unless you bring your instance variable into scope using the this
keyword.
you have to use this if you want to refer to instance variable over local.
精彩评论