Instance Variable Hiding Java Help

Instance Variable Hiding

As you know, it is illegal in Java to two local variables with the same name inside the same or enclosing scopes. interestingly, you can have local variables, including formal parameters to methods, which overlap with the names of the class’ instance variables. However, when a local variable has the same name as an instance variable, the local variable hides the instance variable. This is why width, height. and depth were not used as the names of the parameters to the Box( ) constructor inside Box class. If they had-been, then width would have referred to the formal parameter, hiding the instance variable width. While it is usually easier to simply use different names, there is another way around this situation. Because this lets you refer directly’ to the object, you can use it to resolve any name space collisions that might occur between instance variables and local variables. For example, here is another version of t II Use this to resolve name-space collisions;
Box(double width. double height. double depth) this.width = width; this.height = height; th{n.depth = depth word of caution: The use of this in such a context can sometimes be confusing’ and some programmers are careful not to use local variables and formal parameter names that hide instance variables. Of course, other programmers believe the contrarily=-that a good convention to use the same names for clarity, and use this to overcome the instance variable hiding. It is a matter of taste which approach you loincloth. Allhallows this is of no significant value in the examples just shown, it is very.useful in certain situations.

  • Feel free to send us an inquiry, we will reply back in hours.


Posted on September 17, 2014 in Introducing Classes

Share the Story

About the Author

Back to Top
Share This