Answer the question
In order to leave comments, you need to log in
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);
}
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question