简体   繁体   中英

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?

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 != c1.a .

Since it is final, it will always hold the same value. If you don't declare it static , you will create one variable for each instance of your class. Being static means you declare the variable only once, avoiding unnecessary memory usage.

Declaring a variable as static is more memory effecient. In your example for instance, no matter how many times you create a new A() , because fields x and fields y have been declared static, they will only be allocated memory once. If you do not declare them as static , they will be allocated memory with every new class instance.

It is sensible to declare a final variable that has been initialized like yours as static because it is not able to change, and thus allocating it memory just one time is acceptable.

Essentially, it's to save memory. If the constant is always the same no matter what, then you might as well make it static so that it doesn't get created for each object. You don't want to make it static, however, if the constant is not necessarily the same for each object (for example, if your constant is initialized somewhere in a constructor).

It saves memory as it only allocates for 1 copy of the variable. If you were to make a new instance for a non-static variable for it will make a new copy for that specified instance.

Since they are final they cannot be changed so it would make sense to make them static, so when you make new instances, nothing new is allocated for the variables since they can't even be altered.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM