wood burning stoves 2.0
The moose likes Beginning Java and the fly likes Use A Variable From A Different Class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Use A Variable From A Different Class" Watch "Use A Variable From A Different Class" New topic

Use A Variable From A Different Class

Paul Carron

Joined: Jul 25, 2007
Posts: 3
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

Joined: Oct 30, 2001
Posts: 1970
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.

Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
Vijayender Bandaru

Joined: Nov 21, 2006
Posts: 21
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

Joined: Jul 23, 2007
Posts: 203

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

Joined: Jun 04, 2007
Posts: 320
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.

SCJP - 86% - June 11, 2009
I agree. Here's the link: http://aspose.com/file-tools
subject: Use A Variable From A Different Class
It's not a secret anymore!