Site icon TestingDocs.com

Static variables vs Instance Variables

Introduction

In this tutorial, we will learn the difference between static variables and instance variables in Java language.

Static variables

Static variables belong to the class. There are also known as class variables. countDogObjects is a static int variable in the example. static variables have a single copy of the variable for the class and are independent of the objects of the class. In the example, we use the static variable to count the number of Dog objects created in the program.

We can access the static variable using the class name.

className.staticVariable;

className.getter_method_for_static_variable();

Instance variables

Instance variables have their own copy for each object. These variables are also known as object variables. These variables are used to persist the object state. In the example, the variables name, weight, height of the Dog class are instance variables.

We can access the instance variable using the class name.

objectReference.staticVariable; //inside the class if private

objectReference.getter_method_for_the_variable();//outside the class

Code Listing

Dog.java

package com.testingdocs.tutorial.dog;

//Dog.java
//www.TestingDocs.com

public class Dog {
  private String name;
  private double weight;
  private double height;
  public static int countDogObjects=0;

  // constructor
  public Dog(String name, double weight, double height) {
    this.name = name;
    this.weight = weight;
    this.height = height;
    countDogObjects++;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }
  public double getWeight() {
    return weight;
  }

  public void setWeight(double weight) {
    this.weight = weight;
  }

  public double getHeight() {
    return height;
  }

  public void setHeight(double height) {
    this.height = height;
  }

  public static int getCountDogObjects() {
    return countDogObjects;
  }

  @Override
  public String toString() {
    return "name=" + name + ", weight=" + weight + ", height=" + height ;
  }

}

DogDriver.java

package com.testingdocs.tutorial.dog;

/*********************************************
 * DogDriver.java
 * www.TestingDocs.com
 * 
 *********************************************/
public class DogDriver {

  public static void main(String[] args) {
    Dog dogOneObject= new Dog("Tommy",1.5,0.25);
    Dog dogTwoObject= new Dog("Johny",2.5,0.75);
    System.out.println("Dog One=" + dogOneObject.toString());
    System.out.println("Dog Two=" + dogTwoObject.toString());
    System.out.println("Number of Dog objects created ="+ Dog.getCountDogObjects());
  }

}

 

Sample Output

Dog One=name=Tommy, weight=1.5, height=0.25
Dog Two=name=Johny, weight=2.5, height=0.75
Number of Dog objects created =2

Exit mobile version