java get variable from another class

java get variable from another class

To get a variable from another class in Java, you can make the variable public and access it directly using the name of the class and the name of the variable.

For example, if you have a class MyClass with a public variable myVariable, you can access it from another class like this:

int value = MyClass.myVariable;
Source‮ual.www:‬tturi.com

Alternatively, you can use getter and setter methods to access the variable indirectly. To do this, you can define public getter and setter methods in the class containing the variable, and use them to retrieve and modify the value of the variable.

For example, if you have a class MyClass with a private variable myVariable and public getter and setter methods getMyVariable and setMyVariable, you can access the variable from another class like this:

MyClass obj = new MyClass();
int value = obj.getMyVariable();
obj.setMyVariable(123);

Using getter and setter methods can be useful if you want to add additional behavior when accessing or modifying the variable, or if you want to make the variable final and prevent it from being modified directly.

Note that if the class containing the variable is in a different package, you will need to import the class or use its fully qualified name (i.e. the package name plus the class name) to access it.

Created Time:2017-11-03 22:21:11  Author:lautturi