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:
public class Student{private final int STUDENT_NUMBER;public Student(int idNumber){STUDENT_NUMBER = idNumber;} // End constructorpublic static void main( String args[] ){Student joe = new Student(1234);Student emily = new Student(5678);} // End main} // End Student
But the following set method would be illegal:
// ILLEGAL METHOD: ATTEMPT TO CHANGE THE VALUE OF A FINAL DATA FIELDpublic void setStudentNumber(int idNumber){STUDENT_NUMBER = idNumber; // Error!} // End setStudentNumber
Here is an illustration of the two Student
objects—joe
and emily
—created by the previous main
...