• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Difference between declaring variables.

 
Joy Vergis
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HI,
Please let me know waht is the difference between declaring variables at line no.1 and line no. 2




I thought declaring a variables in the constructor Employee constructor will make the variable for the method getName(). but the same did not happen.

I am a bit confused with instance variable concept. Instance variable are accessible through the object of the class. So I declared it in the constructor itself. Now tha same variable is not accessible outside the constructor in the same class to other methods.

Please help to understand it.



 
John Jai
Rancher
Posts: 1776
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The variable @ line #12 are local variables visible only to the constructor block. Instance variables should be declared outside any method / block in the class. So try declaring the variables @ line #5.
 
Campbell Ritchie
Sheriff
Posts: 48382
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
. . . and why are you suppressing a deprecation warning? That looks suspicious to me.
 
Unnar Björnsson
Ranch Hand
Posts: 164
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The constructor in no different than any other method or code block in terms of scope, variables declared inside a constructor or any other codeblock are not visible outside it. You should move the declaration of name outside the constructor while still giving it value of 'n' inside it.
 
Ted Smyth
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote: . . . and why are you suppressing a deprecation warning? That looks suspicious to me.


Likewise. The getMonth() method of java.util.Date was deprecated some time ago (JDK 1.1, lol, that's some serious backwards compatibility right there).
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic