Check the program, whether there is a problem, if there is, point out the problem, if not, explain the output.
public class HelloB extends HelloA { public HelloB() { } { System.out.println("I’m B class"); } static { System.out.println("static B"); } public static void main(String[] args) { new HelloB(); } } class HelloA { public HelloA() { } { System.out.println("I’m A class"); } static { System.out.println("static A"); } }
A.static A I’m A class static B I’m B class
B.I’m A class I’m B class static A static B
C.static A static B I’m A class I’m B class
D.I’m A class static A I’m B class static B
Answer: C.
Analysis: It involves: static initialization code block, construction code block, and construction method.
When inheritance is involved
, execute in the following order: 1. Execute the static code block of the parent class
static {
System.out.println("static A");
}
Output: static A
2. Execute the static code block of the subclass
static {
System.out.println("static B");
}
Output: static B
3. Execute the construction code block of the parent class
{
System.out.println(" I'm A class");
}
Output: I'm A class
4. Execute the constructor of the parent class
public HelloA() {
}
Output: None
5. Execute the construction code block of the sub-class
{
System.out.println(" I'm B class");
}
Output: I'm B class
6. Execute the constructor of the subclass
public HelloB() {
}
Output: None
, the final output is:
static A
static B
I'm A class
I'm B class
Correct Answer: C