I just would like to clarify this. What is the difference between -
private static int STUDENT_AGE = 18;
and
private static final int STUDENT_AGE = 18;
within the field?
Jon Skeet explained as "not related to a particular instance at all", ok I think I understand it. Then what does final do in this case exactly?
Below code does not work is it because student age is assigned as static final? Does it mean the default age can not be overwritten at all? then is it possible to create the constructor that specify an age other than the default?
private String myName;
private String myAddress;
private int myYearEnrolled;
private String myGender;
private static final int STUDENT_AGE = 18;
public Student(String name, String address, int year, String gender) {
myName = name;
myAddress = address;
myYearEnrolled = year;
myGender = gender;
}
public Student(int age)
{
STUDENT_AGE = age;
}
private static final will be considered as constant and the constant can be accessed within this class only. Since, the keyword static included, the value will be constant for all the objects of the class. private final variable value will be like constant per object. You can refer the java. lang.
Just like an instance variables can be private or public, static variables can also be private or public.
The static keyword means the value is the same for every instance of the class. The final keyword means once the variable is assigned a value it can never be changed. The combination of static final in Java is how to create a constant value.
The main difference between static and final is that the static is used to define the class member that can be used independently of any object of the class. In contrast, final is used to declare a constant variable or a method that cannot be overridden or a class that cannot be inherited.
private static final int STUDENT_AGE = 18;
It's constant declaration. You can't change the value.
private static int STUDENT_AGE = 18;
It's a static declaration but not constant. The value can be changed.
static
means "not related to a particular instance at all" - final
means you cannot change this value after initialization and this value must be initialized.
The combination of final
and static
gives you the ability to create constants. This is no longer recommended in a public way (totally ok for e.g. magic numbers in a private context) as it's not typesafe. Use Enum
post java 1.5 or create your own typesafe enums pre java 1.5 as suggested in Joshua Blochs Effective Java and this question.
Remark: reading this about a year later, I think I need to emphasize that there is nothing wrong with public static final
fields in general, just that named constants should be implemented with enums
or another type safe alternative.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With