D
D
daMage2014-09-22 13:04:58
Java
daMage, 2014-09-22 13:04:58

How does class inheritance work in java?

Help me understand why the code returns 0 instead of 12:

class App {
  public static void main(String[] args) throws Exception {
    Params params = new Params();
    params.MACDFast = 12;
    params.MACDSlow = 16;
    params.MACDMA = 9;

    DSO dso = new DSO(params);
  }
}

class TSParams {
  public int MACDFast;
}

class Params extends TSParams {
  public int MACDFast, MACDSlow, MACDMA;
}

class TS {
  public TS(TSParams params) {
    System.out.println(params.MACDFast);
  }
}

class DSO extends TS {
  public DSO(Params params) {
    super(params);
  }
}

It seems that the TS class constructor works not with an object, but with a static variable of the TSParams class. Actually, how to derive the true value of MACDFast from the TS class?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
bimeg, 2014-09-22
@daMage

In your case, the Params.MACDFast field hid (hided) the TSParams.MACDFast field (there were two of them).
Moreover, the fields are resolved using the compile-time type.
Therefore, in main, you set the Params.MACDFast field, and the TSParams.MACDFast field remained with the default value - 0.
But in the TS constructor, you have the compile-time type - TSParams, so you read the TSParams.MACDFast (0) field, not Params. MACDFast(12).
To fix this in your example, it is enough to remove MACDFast from the Params class.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question