Why data fields should be static and finite

Deitel How to Program a Java Book Says:

The final field must also be declared static if it is initialized in its declaration with a value.

Why is this?

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

I think x and y are the same.
What does qualifier mean statichere?
What is the advantage of a classifier staticthere for monitoring software?

+4
source share
5 answers

xis an instance variable, and yis global.

What does it 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 the main thing:

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

What print:

> create B
> create A
> create A

c1 c2 B, A!

c1.b == c2.b c1.a != c2.a.

, : / b C (c1, c2) a / .

A B: (int, float,...) / .

+3

, . static, . static , , .

+1

. , , new A(), x y , . static, .

final, , , , , .

+1

, . , , , . , , (, - ).

+1

Saves memory since it allocates only one copy of a variable. If you want to create a new instance for a non-static variable, it will make a new copy for the specified instance.

Since they are final, they cannot be changed, so it makes sense to make them static, so when you create new instances, nothing new is allocated for the variables, because they cannot be changed.

+1
source

Source: https://habr.com/ru/post/1626600/


All Articles