aspose file tools*
The moose likes Beginning Java and the fly likes Difference between declaring variables. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Difference between declaring variables." Watch "Difference between declaring variables." New topic
Author

Difference between declaring variables.

Joy Vergis
Ranch Hand

Joined: Sep 14, 2009
Posts: 45
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
Bartender

Joined: May 31, 2011
Posts: 1776
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

Joined: Oct 13, 2005
Posts: 40029
    
  28
. . . and why are you suppressing a deprecation warning? That looks suspicious to me.
Unnar Björnsson
Ranch Hand

Joined: Apr 30, 2005
Posts: 164
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

Joined: May 28, 2008
Posts: 73
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).


Edward Smith
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Difference between declaring variables.