Java instance variables



In the previous program we have learned , how class concept is used in programmatic approach. Generally each object have its own set of instance variables. Now in this chapter we are going to see how different objects access their instance variables.

Live Example : Class With Two Objects (Each have its own copy of Instance Variable

class Rectangle {
  double length;
  double breadth;
}

// This class declares an object of type Rectangle.
class RectangleDemo {
  public static void main(String args[]) {
    Rectangle myrect1 = new Rectangle();
    Rectangle myrect2 = new Rectangle();
    double area1,area2;

    // assign values to myrect1's instance variables
    myrect1.length = 10;
    myrect1.breadth = 20;

    // Compute Area of Rectangle
    area1 =  myrect1.length * myrect1.breadth ;
    System.out.println("Area of Rectange 1 : " + area1);

    // assign values to myrect2's instance variables
    myrect2.length = 10;
    myrect2.breadth = 20;

    // Compute Area of Rectangle
    area1 =  myrect2.length * myrect2.breadth ;
    System.out.println("Area of Rectange 2 : " + area2);

  }
}

Explanation :

Class - Object and instance Variables in Java Programming Language

Each Object has its own set of Instance Variables :

  1. In the above program we have created two objects of the class “Rectangle” , i.e myrect1,myrect2
Rectangle myrect1 = new Rectangle();
Rectangle myrect2 = new Rectangle();
  1. As soon as above two statements gets executed , two objects are created with specimen copy of their instance variables.
  2. In short myrect1’s version of lemgth and breadth gets created . Similarly myrect2’s version of length and breadth gets created.
  3. Using dot Operator we can access instance variable of respective object.

If you want to access instance variable of myrect1 Object –

myrect1.length  = 10;
myrect1.breadth = 20;

If you want to access instance variable of myrect2 Object –

myrect2.length  = 5;
myrect2.breadth = 10;
  1. We can assign different values to instance variables of object. Instance variable of different objects though have same name , they have different memory address , different value.
  2. It is important to understand that changes to the instance variables of one object have no effect on the instance variables of another.