Reputation: 4555
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.
Upvotes: 2
Views: 34402
Reputation: 13066
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
reflection
package .
Upvotes: 0
Reputation: 15758
It depends how your variable is declared. Here is the Oracle tutorial:
http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
Upvotes: 0
Reputation: 3887
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.
Upvotes: 0
Reputation: 10151
a) public
:visible for all classes
b) protected
: visible in subclasses and classes in the same package
c) default
: visible for classes in the same package
This works for variables and method access.
Upvotes: 0
Reputation: 3871
Create an instance of the first class in the other class and simply use its variables, if declared public in the first class.
class Foo
{
public int a=10;
}
In the other class, do this
Foo a=new Foo();
int test = a.value;
Upvotes: 0
Reputation: 11979
Either declare the variable as public:
public class class_one {
public Integer myValue;
}
or create a public getter (preferred), such as:
public class class_one {
private Integer myValue;
public Integer getMyValue() {
return myValue;
}
}
Upvotes: 3
Reputation: 53516
Expose your variable via a getter method and call that method on an instance of the desired class.
Upvotes: 1