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:

Program:

Output:

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:

Program:

Output:

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:

Output:

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 Reply

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