Monday, 14 March 2016

Static vs Non-static in Java

A really good (and tough!) distinction that everyone coding in Java needs to know: the difference between static and non-static variables in Java.

In my opinion, tutorial4us did a great job explaining it. A very good read indeed.

My understanding is that instance (non-static) variables exist in each object (instance of the class). Each object will have its own value/content for each instance variable. Think of the name in a Person class. We define the name as an attribute or property of a person, and each Person object will have its own name.

Static variables exist only inside the class where they are declared. Some call them "class variables" because they are bound to the class, not the object. They are unique and when a new object is instantiated, the object does not get its own copy of it. Rather than using the dot notation with the object (object.nnnn), you would use it with the class (Class.nnnn).

Note that this also applies to, and is also often used with methods!

Think about these example:

public class Test
  public static void main (String args[])
    int[] numbers = {1,2,3,4,5};
    System.out.println( numbers.length ); // =5
    // length (size/number of elements) of the array object
    System.out.println( Math.PI );
    // PI is stored as a static constant inside the Math class
    // we don't need to instantiate a Math object to use PI

No comments:

Class Relationships

Please read these two resources to have a better understanding of class relationships