How to Get Variable From Another Class in Java

In this article, you will learn about accessing a variable from another class in a Java Program.

To be able to program in any programming language, it is very critical to be able to understand how to use the variables according to your need, and thus it makes it very important to be able to understand how to access variables.

Classes and Objects in Java

Classes and Objects are fundamental to Java as it is an object-oriented programming language. Classes are nothing but a basic layout of an entity that could represent a real-life object.

Classes create an object. Classes are general whereas an Object is specific. For example, a class of Vehicles can become the blueprint of any real-world object such as a bike, car, truck, or bus.

Access Modifiers in Java

As the name suggests Java provides access modifiers that can help change the scope of variables, member functions, constructors, etc.

There are four types of access modifiers provided by the Java Language Specification, these are Private, Public, Protected, and Default.

It is important for you to understand the basics of access modifiers as it is one of the helpful methods to get variables from another class that we will discuss further in this article.

Get Variable From Another Class in Java

There are multiple ways to get variable from another class in Java.

Using the Default or Public Access Modifier of the Other Class

The public access modifier has the largest scope out of all the access modifiers of Java. Thus if a variable is declared using the public access modifier it can even be accessed outside of the package as well.

However, in the same package, the default access modifier can also provide unrestricted access to variables within different classes.

When you declare a variable without using any specific access modifier such as public, protected, or private, Java considers it as a default scope.

In the following code, you will observe how the usage of a public access modifier can help in accessing the variable from another class.

You can note that the AnotherClass instance cab be accessed in the Sample class because it was declared as public.

Output:

4

Note that if the package of both of your classes is the same, in essence, both classes are inside the same directory, you may even skip the public keyword and nothing would change.

This is due to the fact that by default, Java gives package-level access to all the variables without any modifier.

Using the Static Member of Another Class

Java enables you to define variables that can be static, instance, or maybe local.

Declaring a variable as static means that the variable’s data will be held inside the static memory of the program, and it will be destroyed after the execution of the program.

In case you do not want to create an instance of the class, you still have an option to use variables of other classes in your class. This can happen if your variable is declared as static in nature.

To understand how you can use the static variable, let us have a look at the following sample code.

Output:

4

As you can see, the static variable can be used by using the class name. This allows us to use the static variable in any class.

Using the Inheritance Concept of Java

Inheritance is one of the pillars of object-oriented programming as implemented in Java.

Inheritance essentially provides all the variables and methods of the parent class to the base class except the private methods and variables.

An example of inheritance can be a class cars that will inherit from the class vehicle, having wheels and engine but specifics involves four wheels and roof, etc.

Java provides the extend keyword to inherit the elements of the base class that are not private.

To understand this concept let us look at the following sample code.

Output:

4

Using the Getters and Setters of Another Class

Like Inheritance, Encapsulation is also one of the pillars of Object-Oriented Programming.

One way to implement encapsulation in the Java Language is by making explicit functions to modify private members of the class.

These explicit functions are generally called getters and setters of that particular member variable.

Implementing getters and setters is fairly simple, easy, and straightforward. You can also modify getters and setters according to some conditions as it is explicitly defined.

To understand how you can get a variable of a class from another class, let us look at the following piece of code.

Output :

4

The get() method of the AnotherClass acts as the getter that provides indirect access to the member variable.

Note that accessing the variable in this way is indirect. It is also safer than other methods.

Using the Singleton Pattern Design for Declaring Global Variables

Singleton Classes in Java are classes that only have one instance of themselves. It has numerous advantages in terms of performance and efficiency in the memory of the program.

You can also implement the Singleton Pattern Design to access variables from another class. This code basically provides a global variable to an entire project, a single line acts as the declaration of a global variable.

Singleton Classes can be instantiated in two ways:

  • Early instantiation.
  • Lazy instantiation.

You can know more about early and lazy instantiation here.

In the following code, we will use the Lazy instantiation. To understand this whole concept let us look at the following sample code.

Output :

4

If you examine carefully, you would notice that you would need two different files of class as both of them are public classes. This is because you can have at most one public class in each file.

The main advantage of using the concept of Singleton Design Pattern is that by using only one single line of code (which in this case is SingletonClass.getinstance().thevariable) anywhere in the project you will directly be able to access the variable making it a go-around of declaring a global variable.

Conclusion

The access modifiers concept is one of the core concepts that may come in very handy for you. However, it should be used with care as it can cause security issues.

Declaring the variable to be static is another shortcut for accessing a member without even creating an instance of a class, however as you can observe it comes with its own set of disadvantages as it will become a very vulnerable variable.

This is all about how to get a variable from another class in Java

Hope you have learned something new and enjoyed reading the article. Stay tuned for more such articles. Happy learning!

Was this post helpful?

Related Posts

  • 24 September

    Increment for Loop by 2 in Java

    Table of ContentsHow to increment for loop by 2 in JavaHow to increment for loop by n in Java In this post, we will see how to increment for loop by 2 in Java. There are several looping statements available in Java and one of them is for loop in java. There are three parts […]

  • 20 September

    Return ArrayList in Java

    Table of ContentsReturn ArrayList in Java From a Static MethodReturn ArrayList in Java From a Non-static MethodConclusion This article discusses cases of returning an ArrayList in Java from a method. An ArrayList in Java is a collection of elements of the same data type under a single variable name. In different cases, you can return […]

  • Check if Object is null Java
    14 March

    Check if Object Is Null in Java

    Table of ContentsComparison Operator to Check if Object Is Null in JavaisNull() Method to Check if Object Is Null in JavanonNull() Method to Check if Object Is Null in JavarequireNonNull() Method to Check if Object Is Null in JavaConclusion An object in Java is an instance of a class. It is a real entity existing […]

  • How to print multiple variables in java
    31 January

    How to Print Multiple Variables in Java

    Table of ContentsWays to Print Multiple Variables in JavaUsing System.out.printUsing System.out.printfPrint Multiple Variables in Java Using LoggerFrequently Asked QuestionsHow Do I Print Multiple Values on One Line in JavaHow to Print Multiple Integers in JavaHow to Print String and Integer in Same Line in Java In this post, we will see how to print multiple […]

  • What is == in java
    01 December

    What is == in java

    Table of ContentsWhat is meaning of == in JavaCode example of ==Object equality using equal to ==The difference between == and equals== in EnumConclusion In this tutorial, we will learn what is == in Java as it is a common lexeme that we will use while developing applications. The == lexeme can be confused with […]

  • Multiple classes in one file in Java
    18 October

    Multiple classes in one file in Java

    Table of ContentsIntroductionMethods to Implement Multiple Classes In One Java Program1) Nested classes2) Multiple non-static nested classes In this post, we will see how to have multiple classes in one file in java. Introduction You need to have any number of classes in a single Java file, but there is a restriction that you can […]

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.