How To Get Variable From Another Class

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 7

How to get variable from another class in Java

Introduction

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 wish, and thus it makes it very
important to be able to understand how to access variables. In this article you will learn
about accessing a variable from another class in a Java Program.

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 which could represent a real
life object. Classes are what creates an object. Classes are general whereas an Object is
specific. For example, a class of Vehicle can become the blueprint of any real world
object such as a bike, car, truck or a bus.

Access Modifiers of Java

As the name suggests Java provides access modifiers which basically 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 which we will
discuss further in this article.

Using the default or public access modifier of the another 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
which is defined without specifying either one of public private and protected, can also
provide unrestricted access to variables within different classes.

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

public static void main(String[] args) {


AnotherClass Ac=new AnotherClass();

System.out.println(Ac.thevariable+2);
}
}
class AnotherClass
{
public int thevariable=2;
}

Output :

In the above code, the publicly declared variable ‘thevariable’ was declared inside the
another class ‘AnotherClass’ which was used directly in the Sample Class, as it was
declared using the public access specifier. Instead of using the public keyword, if nothing
would have been used it would be treated as the default access specified variable.

Using the static member of the another class

Java provides you to define variables which 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 . If
you wish to not make an instance of the class, you have an option to use variables of
other classes in your class if it 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.

public class Sample {

public static void main(String[] args) {


System.out.println(AnotherClass.thevariable+2);
}
}
class AnotherClass
{
static int thevariable=2;
}

Output :

As it can be seen in the above code, the statically declared variable ‘thevariable’ of the
another class ‘Another Class’ was used inside the Sample Class’s main method. The
updated value is shown as the output of the code. The main takeaway you can get from
this code is that you do not need to create an instance of the ‘AnotherClass’ for using the
variable

Using the Inheritance concept of Java

Inheritance is one of the pillars of object oriented programming which the Java Language
is. When a class inherits from another class it basically is a specific version of the base
class it may add new features to an existing blueprint, from which another type of an
object can be made. An example of inheritance can be a class of car which will inherit
from the class of vehicle, having wheels and engine but specifics involves four wheels
and roof etc.

Using the inheritance concept in Java you can extend from another class and access its
variable directly. To understand this concept let us look at the following sample code

class AnotherClass
{
int thevariable=2;
}
public class Sample extends AnotherClass{

public static void main(String[] args) {


Sample sp=new Sample();
System.out.println(sp.thevariable+2);
}
}

Output :

You can observe how the keyword ‘extends’ is used for the implementation of the
inheritance concept in Java. Here, the ‘AnotherClass’ becomes the base class from which
the Sample class inherits the variable ‘thevariable’. As you can see the accessed variable
can be used for manipulations inside the Sample class.

Using the getters and setters of the 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.

class AnotherClass
{
private int thevariable=2;

public int get()


{
return thevariable;
}
public void set(int newnum)
{
thevariable=newnum;
}
}
public class Sample {

public static void main(String[] args) {


AnotherClass Ac=new AnotherClass();
System.out.println(Ac.get()+2);
}
}

Output :

As you can see, a normal get() member function of the class ‘AnotherClass’ was used to
get the access of the variable ‘thevariable’ inside our sample class. In the main driver
function inside the sample class, an instance of ‘AnotherClass’ was created and then the
get() function was called to get the variable’s value for manipulation inside the Sample
Class.

Using the Singleton Pattern Design for declaring global variables

Singleton Classes in Java are classes which only have one instance of itself. 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 and Lazy
instantiation. In the following code, Lazy Instantiation will be used. To understand this
whole concept let us look at the following sample code.

//Class Sample

public class Sample {

public static void main(String[] args) {


System.out.println(SingletonClass.getinstance().thevariable+2);
}
}

// Class Singleton

public class SingletonClass


{
private static SingletonClass instance=null;

public int thevariable=2;

static public SingletonClass getinstance()


{
if(instance==null)
{
instance=new SingletonClass();
}
return instance;
}
}

Output :

After careful examination of the above you would be able to tell that two different files of
class have to be made as both of them are public classes. The main advantages of using
the concept of Singleton Design Pattern is that by using only one single line of code
(which in this case was SingletonClass.getinstance().thevariable) anywhere in the project
will directly be able to access the variable making it as a go around of declaring a global
variable.

Conclusion
These are the different ways that can be used when there is a need to access a
variable of a class from another class. The access modifiers concept is one of the
core concepts that may come very handy for you. However, it should be used with
care. 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.

In this article we also realized the core concepts of Object Oriented Programming :
Encapsulation and Inheritance in our case of accessing the variable from another
class. Encapsulation was implemented using getters and setters concept and
Inheritance was discussed by inheriting another class by using the extend keyword.
Lastly, we discussed a complicated but efficient performing workaround for
declaring a global variable in Java by the use of Singleton Design Pattern.

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!

You might also like