I’m “converting” from .NET to Java. I wonder why a code below is not working
class MyClass{
private final int intVar; //ok
private final Paint paint; //error "Variable paint might not have been initialized"
public MyClass(){
intVar = 12;
initializePaint();
}
private void initializePaint(){
paint = new Paint(); //error "cannot assign a variable to final variable"
}
}
You should initialize final fields at the place where declared in class or in constructor.
Initialization of final fields is allowed in constructor because constructor is called only once while object creation.
As you initialized it in method
initializePaint(), you will get compiler error because this method can be called multiple times and final variable/field is constant and can not be changed. As you would be callinginitializePaint()method multiple times, multiple times initialization of final field which is wrong. Therefore Compiler will give an error for it.