private final static attribute vs private final at

2019-01-02 16:20发布

In Java, what's the difference between:

private final static int NUMBER = 10;

and

private final int NUMBER = 10;

Both are private and final, the difference is the static attribute.

What's better? And why?

20条回答
呛了眼睛熬了心
2楼-- · 2019-01-02 17:08

very little, and static

There isn't much difference as they are both constants. For most class data objects, static would mean something associated with the class itself, there being only one copy no matter how many objects were created with new.

Since it is a constant, it may not actually be stored in either the class or in an instance, but the compiler still isn't going to let you access instance objects from a static method, even if it knows what they would be. The existence of the reflection API may also require some pointless work if you don't make it static.

查看更多
梦寄多情
3楼-- · 2019-01-02 17:13

From the tests i have made, static final variables are not the same with final(non-static) variables! Final(non-static) variables can differ from object to object!!! But that's only if the initialization is made within the constructor! (If it is not initialized from the constructor then it is only a waste of memory as it creates final variables for every object that is created that cannot be altered.)

For example:

class A
{
    final int f;
    static final int sf = 5;

    A(int num)
    {
        this.f = num;
    }

    void show()
    {
        System.out.printf("About Object: %s\n Final: %d\n Static Final: %d\n\n", this.toString(), this.f, sf);
    }

    public static void main(String[] args)
    {
        A ob1 = new A(14);
        ob1.show();

        A ob2 = new A(21);
        ob2.show();

    }
}

What shows up on screen is:

About Object: A@addbf1 Final: 14 Static Final: 5

About Object: A@530daa Final: 21 Static Final: 5

Anonymous 1st year IT student, Greece

查看更多
登录 后发表回答