Is this even possible, few argue its possible and i saw it here too link.. but when i personally tried it gives me compile time errors..
i mean this,
Class A{
private final String data;
public A(){
data = "new string";
}
}
Thanks in advance..
Once you declare a variable final, after initializing it, you cannot modify its value further. Moreover, like instance variables, final variables will not be initialized with default values. Therefore, it is mandatory to initialize final variables once you declare them. If not a compile time error will be generated.
In Java, non-static final variables can be assigned a value either in constructor or with the declaration. But, static final variables cannot be assigned value in constructor; they must be assigned a value with their declaration.
A final variable can be initialized only once. A final variable at class level must be initialized before the end of the constructor.
A variable cannot be modified after it is declared as final. In other words, a final variable is constant. So, a final variable must be initialized and an error occurs if there is any attempt to change the value.
Yes, it is possible. Class is written with small case c. Otherwise your code is perfectly fine (except for identation):
public class A {
private final String data;
public A() {
data = "new string";
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With