Answer the question
In order to leave comments, you need to log in
Calling a child method in a parent's constructor?
public class Solution {
public static void main(String[] args) {
new B(6);
}
public static class A {
private int f1 = 7;
public A(int f1) {
this.f1 = f1;
initialize();
}
private void initialize() {
System.out.println(f1);
}
}
public static class B extends A {
protected int f1 = 3;
public B(int f1) {
super(f1);
this.f1 += f1;
initialize();
}
protected void initialize() {
System.out.println(f1);
}
}
}
public class Solution {
public static void main(String[] args) {
new B(6);
}
public static class A {
private int f1 = 7;
public A(int f1) {
this.f1 = f1;
initialize();
}
---->protected void initialize() {
System.out.println(f1);
}
}
public static class B extends A {
protected int f1 = 3;
public B(int f1) {
super(f1);
this.f1 += f1;
initialize();
}
protected void initialize() {
System.out.println(f1);
}
}
}
Answer the question
In order to leave comments, you need to log in
In the first case, since A.initialize() is marked as private, class B creates its own B.initialize() method. Therefore, the result will be 69, A.initialize() will be executed first, and after B.initialize(). But in the second case, this method is inherited and overridden, so the version of Initialize() from B will be called in the constructor of class A (in java, classes are virtual by default). But since the derived class is initialized after the base class, then the result will be 09 (field f1 in class B has not yet been initialized and contains a standard value, but it is already being output).
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question