Can anybody explain to me the order of the output? Especially, what the "this(D()1" in the constructor causes? Are there some "rules" ijn which order which variable is declared? (static/instance and so on)
Sorry for my bad english.
Can anybody explain to me the order of the output? Especially, what the "this(D()1" in the constructor causes? Are there some "rules" ijn which order which variable is declared? (static/instance and so on)
Sorry for my bad english.
A Java
program executes from the top down in the main()
-method. From there it does whatever the code tells it to do. In your case, it can be summarized as follows:
Prints the line to console.
When creating a new Dog, its superclass (Mammal
) must first be created. The this("D(2)")
calls the other constructor of class Dog
.
From there the superclass Mammal
is instantiated, since it extends DomesticAnimal
, that must be created first. and since the variable da
is declared to be initialized outside the constructor, it is done first.
The constructor completes and prints the line.
The rest of Mammal
is instantiated, same as in (3)
The line is printed after the super class is successfully instantiated. Same as (4)
With all super classes created, class Dog
's attribute outside the constructor is initialized. Same as in (5) and (3).
Line is printed. Same as (6) and (4)
The other constructor method has competed, so the rest of the initially called constructor executes. I.e. the line is printed.