Static vs Instance variables in java

Static Variables

  • Declared by using the keyword static.
  • Static variables are also known as static member variables.
  • Every instance of that class shares the same static variable.
  • If changes are made to that variable, all other instances will see the effect of the change.
  • Static variables are not used very often but can sometimes be very useful.
    • when reading user input using the Scanner class we will declare a scanner as a static variable.
  • That way static methods can access it directly.

Static variable

package anote;

class Car {

    private static String name;

    public Car(String name) {
        Car.name = name;
    }

    public void carName() {
        System.out.println("Car name: " + name);
    }

}

public class Main {
    public static void main(String[] args) {

        Car ferrari_F40 = new Car("Ferrari_F40");
        Car aventador = new Car("Aventador");

        ferrari_F40.carName();
        aventador.carName();
    }
}
Car name: Aventador
Car name: Aventador

Why can name are the same Aventador?

The static variables share the variable between instances.

This particular example, it is better to use instance variable.

Instance Variables

  • They do not use the static keyword.
  • Instance variables are also known as fields or member variables.
  • Instance variables belong to an instance of a class.
  • Every instance has it is own copy of an instance variable.
  • Every instance can have a different value (state).
  • Instance variables represent the state of an instance.

Instance Variables

package anote;

class Car {

    private String name;

    public Car(String name) {
        this.name = name;
    }

    public void carName() {
        System.out.println("Car name: " + name);
    }

}

public class Main {
    public static void main(String[] args) {

        Car ferrari_F40 = new Car("Ferrari_F40");
        Car aventador = new Car("Aventador");

        ferrari_F40.carName();
        aventador.carName();
    }
}
Car name: Ferrari_F40
Car name: Aventador

Leave a Reply

Your email address will not be published.

ANOTE.DEV