• Post Reply Bookmark Topic Watch Topic
  • New Topic

Reference Variable and Instance Variable  RSS feed

 
vinay kalal
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have one confusion. What the relation between Int a and Int b(instance variables) with the reference variables a and b of serialization2 object. Because code is not giving any compilation error.



Thanks in advance
Vinay
 
Ilari Moilanen
Ranch Hand
Posts: 199
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can have varibles of the same name as instance/class variables inside a method. The variables inside the method are used if you do not say differently. And to use the instance/class variables insted you use the "this" keyword.

Please read:
http://download.oracle.com/javase/tutorial/java/javaOO/thiskey.html
 
himanshu.harish agrawal
Ranch Hand
Posts: 47
Java Linux Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Vinay,

The concept which you are looking for is called as Shadowing. As per JLS it is legal to declare two variables with same name but having different scope (in that i think one scope should always be class level scope).

In your code also you are declaring two variables with same name but having different scopes. First is an int having class level scope and other is an object reference variable having method scope. By doing this you are shadowing you instance variable with your local variable in the method.

Even it is legal to declare two variables of same type but different scopes.

Thanks.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
himanshu.harish agrawal wrote:... The concept which you are looking for is called as Shadowing. As per JLS it is legal to declare two variables with same name but having different scope...

That's exactly right. If interested, here are the references:

JLS 14.4.2 - Scope of Local Variable Declarations
JLS 14.4.3 - Shadowing of Names by Local Variables

(It's a good idea to bookmark the JLS. )
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!