I am learning some basic OOP concepts in Java. Consider the following code snippet:
class my_class{
int a;
public my_class() {
System.out.print(a+" ");
a = 10;
System.out.print(a);
}
}
class Main{
public static void main(String[] args) {
my_class my_object = new my_class();
}
}
The output of the following code is: 0 10
According to my understanding:
my_class
is the name of the classmy_object
is the reference of the object I am creatingnew
operator allocates memory and returns it's address which is stored in my_object
my_class()
is the constructor which initializes the object's fields with default value 0 and later assigns it 10Now consider the code:
class my_class{
final int a;
public my_class() {
a=10;
System.out.print(a);
}
}
class Main{
public static void main(String[] args) {
my_class my_object = new my_class();
}
}
From my previous understanding it should have created my_object
with field final int a
set to the default value 0 which should be unchangeable and flag an error at a=10;
but instead it works and prints the output: 10
Where am I going wrong?
You can initialize any final
field once, either in the constructor (that is, each constructor once), or in its declaration.
(Notably, if you want the arguments to the constructor to play a part in the value of the final variable, you must initialize it in the constructor -- otherwise final variables would be kind of useless!)