Search code examples
javastaticfinal

Why should data fields be static and final


Deitel's How To Program Java book says:

A final field should also be declared static if it is initialized in its declaration to a value.

Why is that?

public class A
{
   private final int x = 5;
   private static final int y = 5;
}

I think x and y are the same.
What does the static qualifier matter here?
What is the advantage of the static qualifier up there for software engineering observation?


Solution

  • x is an instance variable while y is global.

    What does that mean?

    Let's look at this example:

    public class A {
        public A() {
            System.out.println("create A");
        }
    }
    
    public class B {
        public B() {
            System.out.println("create B");
        }
    }
    
    public class C {
        private static B b = new B();
        private A a = new A();
    }
    

    Then a main:

    public static void main(String[] args) {
        C c1 = new C();
        C c2 = new C();
    }
    

    Which prints:

    > create B
    > create A
    > create A
    

    c1 and c2 shares the same instance of B while they both create their own instance of A!

    So c1.b == c2.b while c1.a != c2.a.

    So summary: there is only one and the same place/address for field b for every instance of class C (c1, c2) but for field a there are different places/addresses in the different instances.

    The example is a bit oversized with class A and B: Even for simple fields (int, float, ...) is one and the same place/occurrence for a static field in every instance of a class.