P
P
Pavel Dudenkov2015-11-09 19:51:14
Java
Pavel Dudenkov, 2015-11-09 19:51:14

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);
        }
    }
}

In this example, the initialize() method of class A will be called in the constructor of class A, but if you do so, then the method of class B is already called, which did not have time to initialize its variable 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);
        }
    }
}

If I am vaguely aware of the second example (although I still don’t fully understand it), then I don’t understand the first one at all.
Why narrowing the scope (private) allows you to call the parent's method?
Please also explain what is actually happening and why in the example where the child method is called from the parent constructor.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vitaly Vitrenko, 2015-11-09
@viperz

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 question

Ask a Question

731 491 924 answers to any question