Final Fields and Static Fields
Explore how to declare final fields for immutable object data and static fields for shared class data in Java. Understand when to use static and final modifiers, how they affect data storage, and the conventions for naming constants. This lesson helps you write clearer, more efficient Java classes by properly managing constants and shared variables.
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 ...
...