Core Java

Instance Variable Java Example

In this article, we will show Instance Variable Java Examples. Firstly we will talk about what instance variables are in general and the reason that we use them. After that, we will analyze the difference between instance, local and static variables. Last but not least we will demonstrate some examples.

1. Introduction

instance variable java

First of all, we need to know that the Variables are classified into three types:

  • Local Variables
  • Instance Variables
  • Class/Static Variables

Local variables in Java are variables that declared in the body of the method and you can use it only in the method. For example, if you try to use it in other methods of class it will print that this variable doesn’t exist. Here is an example:

Local.java

public class Local {
public static void main(String args[]) {
	int n=4;
	int Num=Number(n);
	i=1;// Error :i cannot be resolve to a variable
	System.out.println(Num);
}
public static int Number(int j) {
	int i = 0;
	i=i*j;
	return i;
}
}

As you can see above, at line 5 eclipse will throw an error (i cannot be resolved to a variable). The reason for this error is that “i” was declared in a method so the rest of the class doesn’t know what it is.

Static variables are created and shared among all the instances of the class. Memory allocation for such variables only happens once when the class is loaded in the memory. Here is an example:

Stc.java

public class Stc {
	 static int count=10;
	   public void incr()
	   {
	       count++;
	   }
	   public static void main(String args[])
	   {
		   Stc ob=new  Stc();
	       ob.incr();
	       System.out.println("Count is="+ob.count);
}
}

We will analyze the instance variables later.

2. Technologies used

The example code in this article was built and run using:

  • Java 1.8.231(1.8.x will do fine)
  • Eclipse IDE for Enterprise Java Developers-Photon

3. What is an instance variable

An instance variable is a variable defined in a class in which each instantiated object of the class has a separate copy or instance. These types of variables belong to an instance because of that the instance variables belong to an object and an object is an instance of a class. The first and most important thing that we see at a variable of that type is that it hasn’t got a value. The declaration of an instance variable is:

public class Animals{
int mammals_name;// The mammals_name is an Instance Variable 
}

3.1 Important attributes of an instance variable

Some important attributes of an Instance Variable are:

  • Instance variables are declared in classes but outside of a constructor a method or a block.
  • Instance variables are created when an object is created with the use of the keyword ‘new’ and destroyed when the object is destroyed.
  • Instance variables can be declared in the class level before or after use.
  • An instance variable can be visible by constructors, methods, and blocks in a class.
  • An instance variable can be accessed by calling the variable name inside the class.
  • When space is allocated for an object in the heap, a slot for each instance variable value is created.
  • Instance variables hold values that must be referenced by more than one method, constructor or block, or essential parts of an object’s state that must be present throughout the class.
  • Access modifiers can be given for instance variables.
  • Instance variables have default values.

4. Keywords accepted before instance variable’s name

First of all, we must understand is the syntax of an Instance Variable. The syntax is:

[Access modifier][Type][Name/identifier]; 

For example:

 public double Number;

Now let’s analyze the syntax:

Access Modifier: An instance variable can be declared public, private, protected and default. When we do not want our variable’s value to be changed out-side our class we should declare them private. Public variables can be accessed and changed from outside of the class.  The access level of a protected variable is within the package and outside the package through child class. Last but not least, the access level of a default modifier is only within the package.

Type: At this point, we declare what type we want our variable to be. For example, a variable can be int, String, double, boolean, etc.

Name/identifier: Is the name that we can give at the instance variable.

5. Differences between instance, local and static variables

5.1 Instance variables vs local variables

The local variables are not visible or accessible from outside of their scope which can be determined by {} in contradiction with instance variables that are visible on all part of the code based on the access of the modifier(public, private, protected).The only public can be accessed from outside while protected and private can be accessed from subclass and class itself. From the local variables side, the only modifier which is applicable to a local variable is the final which helps local variables to be visible inside of an anonymous class.

5.2 Instance variables vs static variables

Instance variables are per instance (object) basis. These are also referred to as non-static variable and initialized when you create an instance of any object using new() operator or by using other methods like reflection. On the other hand, Class variables are declared using static keyword and they have exact same value for every instance. Instance variables initialized when an instance is created unlike with static variables which are initialized when the class is loaded first time at JVM memory.

6. Instance Variable Java Example

Here we can show you an example to explain to you and understand how to use instance variables:

Instance_ex.java

public class Instance_ex {
	double speed;
    int horsepower;
 
    //Setters and Getters
    public double getSpeed() {
        return speed;
    }
 
    public void setSpeed(double speed) {
        this.speed = speed;
    }
 
    public int gethp() {
        return horsepower;
    }
 
    public void setGear(int horsepower) {
        this.horsepower = horsepower;
    }
}

Car.java

public class Car {
	public static void main(String[] args) {
	Instance_ex cr = new Instance_ex();
	 
    cr.setSpeed(100);

    System.out.println(cr.getSpeed());

    Instance_ex Audi = new Instance_ex();

    Audi.setSpeed(20);

    System.out.println(Audi.getSpeed());

}
} 
 

The output is:

100.0
20.0

In this example, we set up the Instance_ex instances with a speed using setSpeed and then we print the speed using “getSpeed”.

At the class Car, we use the instances “Audi” and “cr”. Each instance is passed a speed and then it is printed with the help of the appropriate get method.

7. Download the Source Code

That was an Instance Variable Java Example.

Download
You can download the full source code of this example here: Instance Variable Java Example

Ioannis Makrygiannakis

John is an undergraduate student at the Department of Informatics of Athens University of Economics and Business. He is specialized in Databases, Knowledge Management, Information Systems and Information Security. In his free time he loves learning new things with regard to programming and network security.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button