0

It's about the following situation:

public class A {
   int x=3;
   public A() {
      setX(x-3);
   }
   void setX(int z) {
      this.x = z; 
   }
}


public class B extends A        {
   static int x = 7;
   void setX(int z) {
      x = z;
   }
}


public class Main {
   public static void main(String[] args) {
      A ab = new B();
      System.out.println(B.x);
   }
}

Output: 0

I'm already familiar with the fact, that the method of the subclass is executed in when we create an object that way.

Judging by the output, the method setX in class B takes the inherited x as argument, but has a sideeffect on the static variable. Is there a name for this behaviour or a more general explanation? Someone who doesn't know better could for example think, that the method takes the static variable as argument and has a sideffect on the inherited variable.

Karl
  • 63
  • 6
  • The output is not 3, as you say. The output is 0. – Erwin Bolwidt Mar 18 '18 at 03:20
  • Yes, i changed that in the question now. – Karl Mar 18 '18 at 03:25
  • 2
    *"Is there a name for this behaviour or a more general explanation"* - for what? Note that `B.x` has **absolutely zero** to do with `x` inside `A`, they are 100% unrelated. You are simply calling a method with a parameter, that method got overridden and that is it. – luk2302 Mar 18 '18 at 03:28
  • 1
    did you meant `ab.x` or `B.x` in `System.out.println(B.x);` ? – rahulaga-msft Mar 18 '18 at 06:14

1 Answers1

0

This should be the abstract execution flow:

  1. Constructor of B gets invoked. Implicitly the default constructor of A gets invoked.
  2. Inside A's constructor setX(x-3) is called. For type A x is defined as a package private member initialized with 3, this will result in setX(0) beeing called.
  3. Polymorphism kicks in: A ab is of type A at compile time, but of type B at runtime. This results in setX(0) of type B beeing called.
  4. The static variable x is set to 0.
sn42
  • 2,353
  • 1
  • 15
  • 27