...

/

Final Fields and Static Fields

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:

Press + to interact
public class Student
{
private final int STUDENT_NUMBER;
public Student(int idNumber)
{
STUDENT_NUMBER = idNumber;
} // End constructor
public 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:

Press + to interact
// ILLEGAL METHOD: ATTEMPT TO CHANGE THE VALUE OF A FINAL DATA FIELD
public void setStudentNumber(int idNumber)
{
   STUDENT_NUMBER = idNumber; // Error!
} // End setStudentNumber

Here is an illustration of the two Student objects—joeand emily—created by the previous main ...

Access this course and 1400+ top-rated courses and projects.