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?