0

I have two classes one is:

public class Emp {
    String name;
    static int bankVault;
    }

and the other one is:

public class TestEmp {
public static void main(String[] args) {
    Emp emp1 = new Emp();
    Emp emp2 = new Emp();
    emp1.bankVault = 10;
    emp2.bankVault = 20;
    System.out.println(emp1.bankVault);
    System.out.println(emp2.bankVault);
    System.out.println(Emp.bankVault);
    }
}

The output is:

20
20
20

Is this because of the static word? Shouldn't the first System.out.println return 10?

Sempliciotto
  • 107
  • 1
  • 2
  • 6
  • this is the sample to show how "static" works. you have only one bankValault. so you always get same value – Adem Dec 10 '14 at 11:53
  • See [Understanding Class Members](https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html) in Oracle's Java Tutorials. – Jesper Dec 10 '14 at 11:54
  • 10 will be overridden with 20, that is with latest value. Always one value can set to static fields. – janasainik Dec 10 '14 at 11:57

2 Answers2

4

Yes, it is because of the word static. The use of static means you don't need an instance of an object to access it.

It can be accessed with Emp.bankVault. The property is initialized when the class Emp is loaded so there is no need for an instance of Emp object.

Once it's set, it will have the same value regardless of the Emp instance you use to read it from.

MihaiC
  • 1,618
  • 1
  • 10
  • 14
2

Yes, static means "one per class" not "one per instance". Once you modify it you modify it for ALL instances.

Lucas
  • 3,181
  • 4
  • 26
  • 45