Java - why does it print zero?

public class Base {
public Base() {
    x = 0;
    bar();
}

public Base(int x) {
    this.x = x;
    foo();
}

public void foo() {
    System.out.println("Base.foo : " + x);
}

private void bar() {
    System.out.println("Base.bar:" + x.toString());
}

protected Integer x;
}

    public class Derived extends Base {
       public Derived() {
       bar();
       }
       public Derived(int x, int y) {
         super(x);
         this.y = y;
       }
       public void foo() {
         System.out.println("Derived.foo : " + x + ", " + y);
       }
       public void bar() {
         System.out.println("Derived.bar:" + x.toString() + ", " + y.toString());
       }
       private Integer y;


       public static void main(String[] args) {
        Base b = new Derived(10, 20);
      }
}

Why does it print "Derived.foo:" 10, nulll, not 20 instead of null? y is Derived's private variable, and it was initialized with 20. in its area. So why is it null?

+5
source share
8 answers

Because the super constructor is first called ( super(x)). This superconstructor calls the foo method. The Derived constructor then initializes y to 20 ( this.y = y). Therefore, when foo is called, yit is not yet initialized.

It is bad practice to call redefined methods in constructors because, as you just noticed, it can call redefined methods on partially constructed objects.

+7
source

println foo, Base, Derived ( super) y. .

+2

, (Base) Derived.foo() , ​​- y.

, :

main(...)
Derived(10,20) (start constructor)
Base(10) (start constructor)
this.x = x
foo() (calls Derived.foo() which prints the message you see)

this.y = y
+2

, :

  • Derived(int x, int y)
  • Base(int x)
  • x
  • foo()
  • println()
  • y

, y . null.

, , .

+2

y . , foo() null y.

+1

Derived.foo(), Super-Constructor, 20 . null.

+1

, , - . , .

That way you could keep track of that y will not be initialized.

Good luck Rule

+1
source

because y was not initialized when foo () is called in the constructor of the base class.

the chain goes main -> Derived (x, y) -> Base (x) -> initialise x, foo (). However, since you are launching a call inside Derived that overrides foo (), the derived foo () is actually executed by the interpreter.

+1
source

All Articles