File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Use A Variable From A Different Class

 
Paul Carron
Greenhorn
Posts: 3
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can I use a variable in one class that has been declared in a different class? If so how do I access it?
 
Peter Chase
Ranch Hand
Posts: 1970
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you mean an "instance variable" (a.k.a. "field") of another class, then you can access it if its access modifier allows it. If it is "private", you can't access it(*). If it is package-private or "protected", you may be able to. If it is "public", you can.

If you mean a local variable declared within a method of another class, then you can never(*) access that variable from another class.

Which did you mean?

Note that direct access to the non-final fields of another class is bad style. Fields should usually be declared "private" and should be accessed from outside by "getter" and/or "setter" methods. This reduces coupling between classes.

Instance fields that are "final" are sometimes OK to access directly from another class, though it's usually still better style to use "getters".

Fields that are "static final" are constants, and OK to access directly from another class, where that other class needs that constant.

(*) Some exceptions, involving inner and nested classes, which we'll gloss over in this Beginner forum.
 
Vijayender Bandaru
Greenhorn
Posts: 21
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes.Peter lists all possible scenarios.As he mentioned already,it is a good practice to follow Java encapsulation.What is your scenario?
 
subodh gupta
Ranch Hand
Posts: 203
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I think your question covers all the access specifiers, concept of inner and nested classes, inheritace and aggregation, static and instance variable.

Look this is the scope of your question so you really want me to write half of the java here!!! i think better you read all the above things and post the doubts here.
 
Bob Ruth
Ranch Hand
Posts: 320
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would answer you this way:

1) read on the principle of encapsulation,

2) read on access modifiers,

3) read on the difference between static and instance members,

4) read and make sure that you know exactly what "local" variables are, where they are stored, and what is their scope and lifetime,

and you will know this answer and many others.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic