Access a Variable From Another Class in Java

Mohammad Irfan Dec 21, 2022 Jun 07, 2021
  1. Access Static Variables in Java
  2. Access Instance Variables in Java
  3. Access Variables in a Subclass in Java
Access a Variable From Another Class 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

Related Article - Java Class