2
class Main {

  public static void main(String[] args) {
    new B();
  }

  public static class A {

    String f1 = "300";

    public A(){
      init();
    }

    protected void init(){}
  }

  public static class B extends A {

    private String f1 = "3";

    public B(){
      super();
      init();
    }

    protected void init(){
      System.out.println(f1);
    }
  }
}

Output:

null
3

Can anyone explain to me the first line of the output? If I delete the line String f1 = "300";, it still has the same output also.

I have tried that if I declare some variables in B and invoke it in init() and all of it will be null in the constructor of A. In other words, my question is I want to know the reason for those variables being null at that point.

  • 3
    At the time `super()` is called from the `B` constructor, field `f1` in `B`, which is entirely separate from field `f1` in `A` (see [Hiding Fields](https://docs.oracle.com/javase/tutorial/java/IandI/hidevariables.html)), has not been assign yet, so it is null. Because `init()` is overridden, when `A` calls `init()`, it calls the `B` method, which then prints the (so far) uninitialized value. – Andreas Apr 26 '20 at 04:55
  • Thanks a lot! Please help me with another question. Why when A calls ```init()```, it does not invoke ```f1``` in ```A```? Sorry if it is a no-point question. – Chong you yuan Apr 26 '20 at 05:04
  • I already told you: "Because `init()` is **overridden**, when `A` calls `init()`, it calls the `B` method". --- Seems you need to (re)read the section about [polymorphism](https://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html) in your Java learning guide, to learn about method overriding. – Andreas Apr 26 '20 at 05:08
  • Because the assignment happens *after* the `super()` call. As I said: It hasn't been assigned **yet**. – Andreas Apr 26 '20 at 05:24

0 Answers0