There is a code which is given as a task for a junior Java developers. I use Java during five years and this piece of code completely confusing me:
public class Main {
String variable;
public static void main(String[] args) {
System.out.println("Hello World!");
B b = new B();
}
public Main(){
printVariable();
}
protected void printVariable(){
variable = "variable is initialized in Main Class";
}
}
public class B extends Main {
String variable = null;
public B(){
System.out.println("variable value = " + variable);
}
protected void printVariable(){
variable = "variable is initialized in B Class";
}
}
The output will be:
Hello World!
variable value = null
But if we change String variable = null;
to String variable;
we will have:
Hello World!
variable value = variable is initialized in B Class
The second output is more clear for me. So, as far as I know the sequence of inizialisation in Java like this:
Also there is post which describes the behavior of the this
keyword in context of a superclass - Calling base class overridden function from base class method
Based on the rules given above, I assume to have sequence like this:
B
;Main
;main.variable
with null;Main
;b.printVariable()
in class Main
; (Why doesn't it call main.printvariable
? We don't have this
key word here.)b.variable
"variable is initialized in B Class"B
;b.variable
with null value, am I right?;B
executedPlease, can someone give a complete and full explanation of how this inheritance inizialisation sequence works. And why changing String variable = null;
to String variable;
leads to another output.
Instantiation: The new keyword is a Java operator that creates the object. Initialization: The new operator is followed by a call to a constructor, which initializes the new object.
A Sequence is a data structure containing musical information (often an entire song or composition) that can be played back by a Sequencer object. Specifically, the Sequence contains timing information and one or more tracks.
To create an object of a named class by using an object initializer. Begin the declaration as if you planned to use a constructor. Type the keyword With , followed by an initialization list in braces. In the initialization list, include each property that you want to initialize and assign an initial value to it.
The sequence is:
So basically, the super object Main() is constructed before any intialisation events of class B. Which means variable=null occurs later. This makes sense as otherwise B could break the initialisation of Main.
Joshua Bloch covers a lot of good ground in his effective java book about how dangerous inheritance is to get right, I would recommend it.
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