How would I go about accessing data in one java class from another one? For example, I declare an integer with a value in class_one.java and want to make use of that data in class_two.java.
-
I know this question is very simple, but I'm trying to learn and I often don't know where to start when I get stuck like this.THE DOCTOR– THE DOCTOR2013-01-24 19:56:49 +00:00Commented Jan 24, 2013 at 19:56
-
3You need to go through some good Java Tutorial. Oracle tutorial would be a good starting point.Rohit Jain– Rohit Jain2013-01-24 19:57:22 +00:00Commented Jan 24, 2013 at 19:57
-
I realize that I have a lot to learn. However, that doesn't answer my question.THE DOCTOR– THE DOCTOR2013-01-24 19:59:01 +00:00Commented Jan 24, 2013 at 19:59
-
1Yes, Mr Doctor. You have to learn a lot. So, do that! Search for java tutorial for beginners. Take your time and learn. Do not ask trivial question: they can cause damage to your reputation.AlexR– AlexR2013-01-24 20:02:21 +00:00Commented Jan 24, 2013 at 20:02
-
I most certainly am, but in the meantime I wanted to find an answer so I can make a little more progress with what I'm working on. Do not be rude as that can cause damage to your reputation.THE DOCTOR– THE DOCTOR2013-01-24 20:07:43 +00:00Commented Jan 24, 2013 at 20:07
7 Answers
Expose your variable via a getter method and call that method on an instance of the desired class.
Comments
One one is to build a "get" function which will return the desired value
such as
public int getA(){
return a;
}
Another easy solution would be to use static variables. Put the "static" keyword before a variable:
static int a=5;
and to access the variable you use the class:
Class_One.a;
this would use the variable as if it were inside the same class.
Comments
It depends how your variable is declared. Here is the Oracle tutorial:
http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
Comments
You can access a variable of one java class in other java class using either of the following ways:
- Declaring the accessing variable as public and accessing it directly in other class. But You should avoid it as it leads to tight coupling.
- Declaring the accessing variable as private and accessing it via getter Method . It is the preferred way of accessing variables as it keeps the variable safe from accidentally changing in other class.
- Using
reflectionpackage .