0
public class FinalClassVariable {
    public static void main(String[] args) {
        ClassVariable classVariable = new ClassVariable();
        System.out.println("Value of PI accessed thorugh class itself = "+ClassVariable.PI);
        //System.out.println(ClassVariable.E);
        System.out.println("Value of PI accessed thorugh object = "+classVariable.PI);
        System.out.println("The value of constant E = " + classVariable.E);
    }
}

class ClassVariable {
    public static final double PI = 3.14;

    public final double E = 2.7182818284590452353602874713527; 
}

The main difference between the variables 'PI' and 'E' we can access 'PI' through both class name as well as object and 'E' is accessed only through object

And both of these are constant we don't change their value.

I have completed my course in java from Universidad Carlos III de Madrid University and also watched videos of Stanfort University by Mehran Sahami

Both of these guy recommend to use keyword static with the final.

My question is that if we can create constants just by declaring it final then why we have to declare it static as well? The static also compromises the concept of OOP.

Is there any subtle difference between these two declarations? And which one is best to use in our applications?

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
Mahesh
  • 27
  • 7
  • No, `static` does not automatically compromise OOP. There are usually good reasons to avoid `static` **variables** in OOP, but they do not apply to constants. This is an example of how people take useful principles and oversimplify them, to the point where they can become destructive myths. – ajb Jul 16 '15 at 05:49

2 Answers2

4

If you declare a constant using a non static member, each instance of your class would have its own copy of it, which is wasteful, since it's a constant, and all the copies will have the same value. Therefore static final makes more sense - there will only be one copy of this constant. In the case of constants such as PI and E, you should always use static final.

A final instance member (i.e. non static) makes sense if the value of that member is initialized once (usually in the constructor), but can be different for different instances of the class.

Eran
  • 387,369
  • 54
  • 702
  • 768
1

static members are shared by all the instances of the class where as the non static members are created once per instance creation.

Why would you have a constant value created differently for each of the instances? Its meaningless right..

Thus, static final is the choice.

TryinHard
  • 4,078
  • 3
  • 28
  • 54