Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should data fields be static and final

Tags:

java

static

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?

like image 868
eneski Avatar asked Mar 14 '23 11:03

eneski


1 Answers

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.

like image 190
Jean Logeart Avatar answered Mar 21 '23 09:03

Jean Logeart