How to Access Variable From Another Class in Java?

In this article, we will learn how to access variable from another class in java.

There are two ways to get variables from another class.

  1. Create an object of another class in the main class
  2. Extend another class in the main class

Let us take a look at both these methods one by one with the help of sample programs.

Method 1: Create Object of Another Class in Main Class

In the following example, to access the variable ‘a’ of class A, we create its object in another class B. After that, we use this object to use the value of variable ‘a’ in class B. Note that if we do not initialize this variable, then its default value is taken to be zero.

Syntax:

objName.variable_name

Program:

//Parent class
class A
{
    int a = 10;//instance variable
}

//Child class
class B{
        public static void main(String[] args)
        {
             A obj = new A();
             System.out.println(obj.a);
        }
 }

Output:

10

Method 2: Extend Another Class in Main Class

If we wish to access a variable from another class, we have a keyword, ‘extends’, which we can use in the child class. Using it, the child class can inherit all the properties of the parent class.

Syntax:

public class_A extends class_B

Program:

// parent class
class A {
    int a = 10; //instance variable
}

// child class
class B extends A {
    public static void main(String args[]) 
    {
        B obj = new B();
        System.out.println(obj.a);
    }
}

Output:

10

In the above program, we created two classes, namely ‘A’ and ‘B’. In class ‘A’, we defined an instance variable ‘a’ with a value of 10. The other class ‘B’, extends the class ‘A’ using the ‘extends’ keyword. So, it can use the instance variable of class ‘A’ by creating its object. So, the child class inherits all the properties of its parent class.

If we wish to use an instance variable, then we have to use objects to call them. Every time you create a new object from a class, you get a new copy of each of the class’s instance variables. These copies are associated with the new object. So, each and every instance variable is accessed by the object.

Program:

class A {
    int a ; //instance variable
}

public class B extends A {
    public static void main(String args[])
    {
        B obj  = new B();
        
        System.out.println(obj.a);
        
        obj.a =  3;
        System.out.println(obj.a);
    }
}

Output:

0

3

In the above example, the default value of a is 0 and we updated its value to 3 using an object.

So, that’s all about accessing variables from another class.

Leave a Comment

Your email address will not be published. Required fields are marked *