Rahul Raj
Rahul Raj

Reputation: 3459

Final variable values

Let's say we have an immutable class:

public final class Student
{
  final String name;
  final int regNo;

  public Student(String name, int regNo)
  {
      this.name = name;
      this.regNo = regNo;
  }
  public String getName()
  {
      return name;
  }
  public int getRegNo()
  {
      return regNo;
  }
}

Let's say we have created final variables so that their values cannot be changed after object creation. The values for name and regNo are not yet defined here. But I do have a question. We know that if we dont assign values to them, it will take default values. So, if I dont assign any values, it will be

name = null & regNo = 0

So my question is, if its already get assigned to default values, how can we assign values to them at later point?

Upvotes: 0

Views: 99

Answers (2)

Costi Ciudatu
Costi Ciudatu

Reputation: 38195

Those values will indeed be null and 0 before initialisation:

public static final class Student
{
    final String name;
    final int regNo;

    public Student(String name, int regNo) throws NoSuchFieldException, IllegalAccessException {
        System.out.println("BEFORE ASSIGNMENT:");
        System.out.println(getName());
        System.out.println(getRegNo());

        this.name = name;
        this.regNo = regNo;

        System.out.println("AFTER ASSIGNMENT:");
        System.out.println(getName());
        System.out.println(getRegNo());
    }
    public String getName()
    {
        return name;
    }
    public int getRegNo()
    {
        return regNo;
    }

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        new Student("Rahul", 3);
    }
}

Prints:

BEFORE ASSIGNMENT:
null
0
AFTER ASSIGNMENT:
Rahul
3

The compiler just won't let you use those values directly before initialisation. Also, it forces you to assign them once (and only once) while the object is constructed, and never re-assign them afterwards.

Upvotes: 1

enator
enator

Reputation: 2599

Since you don't have any default constructor (also, can't have any other constructors without assigning values to final variables - it will throw compilation error if you tried) - you won't be able to instantiate any Student object without giving name and regNo.

And whatever you give while creating new Student will be final.

Upvotes: 0

Related Questions