Access a Variable From Another Class in Java
- Access Static Variables in Java
- Access Instance Variables in Java
- Access Variables in a Subclass in Java

This tutorial introduces how to call a variable from another class in Java. We’ve included some example programs you can follow to execute this project.
Access Static Variables in Java
A variable defines as the name used for holding a value of any type during program execution. In Java, a variable can be static, local, or instance. If a variable is static, we can access it by using the class name. If a variable is an instance, we must use a class object to access the variable. Let’s understand further through the examples we have.
In the program below, we are accessing the static variable of the Test
class in SimpleTesting
by using the class name. See, we did not create the object of the class; this is how we can access static variables anywhere in the Java source code.
public class SimpleTesting{
public static void main(String[] args) {
Test t = new Test();
t.add(10, 20);
int result = Test.sum; // accessing variable
System.out.println("sum = "+result);
}
}
class Test{
static int sum;
void add(int a, int b) {
sum = a+b;
}
}
Output:
sum = 30
Access Instance Variables in Java
Here, we are accessing instance variables from another class. See, we used the object of the Test
class to access its instance variable. You can only access instance variables by using the class object. Check the sample program below.
public class SimpleTesting{
public static void main(String[] args) {
Test t = new Test();
t.add(10, 20);
int result = t.sum; // accessing variable
System.out.println("sum = "+result);
}
}
class Test{
int sum;
void add(int a, int b) {
sum = a+b;
}
}
Output:
sum = 30
Access Variables in a Subclass in Java
Suppose a class inherits another class; the variables of the parent class become implicitly accessible inside the subclass. You can access all the variables by using the subclass object, and you don’t have to create an object of the parent class. This scenario only happens when the class is extended; otherwise, the only way to access it is by using the subclass.
Here’s the example code.
public class SimpleTesting extends Test{
public static void main(String[] args) {
SimpleTesting st = new SimpleTesting();
st.add(10,20);
System.out.println("sum = "+st.sum);
}
}
class Test{
int sum;
void add(int a, int b) {
sum = a+b;
}
}
Output:
sum = 30
Related Article - Java Variable
- Java Synchronised Variable
- Difference Between Static and Final Variables in Java
- Set JAVA_HOME Variable in Java
- Counters in Java
- Increase an Array Size in Java
Related Article - Java Class
- Make Private Inner Class Member Public in Java
- Decompile Java Class
- Allergy Class in Java
- Inner Class and Static Nested Class in Java
- Class Constant in Java
- Friend Class in Java