The scope of variables in Java – Part 2

Next to Part 1, let’s take a look at the remaining two scopes of variables in Java, and look at the case of variables with the same name but different in scope, how Java handle that.

The variable is inside an object

The variable is inside an object, or called instance variables, which is valid for one life cycle of an object. They are defined inside a class but outside of all methods and it can be accessed by non-static methods inside that class.

The example below of variable a is an instance variable:

The scope of a variable is inside an object wider than a variable inside a method or as a parameter of a method. Because it can be accessed inside all methods within that class and can be accessed from other classes if it is defined with the appropriate access modifier.

For example:

The scope of variables in Java – Part 2

The static variable of a class

The static variable of a class, or called class variables, is defined using the static keyword. This variable belongs to the class, does not belong to the object of that class, and the value of this variable is shared among all objects of that class, meaning that its value will be the same for all objects.

The NAME variable below is a static variable:

We do not need to initialize the object to be able to access the value of the static variable. They can be accessed using the names of the classes that they are defined in.

For example:

The scope of variables in Java – Part 2

Or use the object to access static variables are still:

The scope of variables in Java – Part 2

The scope of a static variable is that it can be accessed from any object of the class that defines it and also objects of other classes if it is defined with the appropriate access modifier.


Variables have the same name but different scope

In a class, we cannot define a static variable and an instance variable with the same name.

The scope of variables in Java – Part 2

Both variables are in a method and variables are parameters of a method, and we cannot define the same name.

The scope of variables in Java – Part 2

But we can define a variable in the method with the same name as the static variable or instance variable. For example:

The scope of variables in Java – Part 2

Add Comment