Final Fields and Static Fields
In this lesson, we will discuss the final and static modifiers.
We'll cover the following...
Final data fields
As we learned in a previous chapter, the objects of a class ordinarily have their own copies of the class’s data fields. We called these variables instance variables since they belong to the object, or instance, of the class. When objects of a class have an instance variable whose value is constant, those values might vary from object to object.
For example, each object of a class Student could be given a fixed student number when it is created. The data field in Student could be declared as:
private final int STUDENT_NUMBER;
Because Student_Number is final, the class’s constructors, but no other methods could assign it a value. That is, the constructor could be defined as:
But the following set method would be illegal:
Here is an illustration of the two Student objects—joeand emily—created by the previous main method:
✏️ Programming tip
You should declare a data field as final if its value will be initialized once when an object is constructed and will not change after that time. Doing so allows the compiler to check that no other code changes the field’s value. ...