How do I initialize a final field in constructor’s body?

It’s not possible to assign a final field in a constructor body. The final field needs to be assigned before the constructor body, in the initializer list or on declaration:

class ClassName
{
    final OtherClass field = new OtherClass(); // Here

    ClassName()
        : field = new OtherClass() // or here 
    {
     
    }
}

As you can’t use this in the initializer list or on the declaration, you can’t do what you plan to do.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)