Pre-constructor initialized variable properties in java
In Java, programming variables can be initialized before calling a constructor.
public class StockGraph extends JPanel {
public boolean runUpdates = true;
double TickMarks = 18;
double MiddleTick = TickMarks / 2;
double PriceInterval = 5;
double StockMaximum;
double StockMinimum;
Random testStockValue;
DecimalFormat df = new DecimalFormat("#.000");
LinearEquation StockPriceY;
public StockGraph(int AreaInterval, int Time, int StockID) {
}
}
What are the properties of these variables?
Does MiddleTick
it change when changed TickMarks
?
When are these variables initialized?
In particular, public boolean runUpdates = true;
. Since no initialization is required, so how can you call StockGraph.runUpdates
to access the variable?
source to share
What are the properties of these variables?
These are instance variables that are assigned a default value.
Does MiddleTick change dynamically when TickMarks change? When do these variables get initialized?
No MiddleTick
will use TickMarks
that is available at MiddleTick
ie initialization time at instantiation time.
in particular, public boolean runUpdates = true; Since no initialization is needed, because StockGraph.runUpdates can be called to access the variable?
runUpdates
cannot be directly accessed (StockGraph.runUpdates) without an instance, since it is not an instance field, not a static field.
There are different ways to initialize fields in java, depending on the need and readability of the code. This article sheds light on this:
source to share
These variables are not initialized before the call to the constructor, instead they are copied into the constructor immediately after the call super()
. The Java Tutorials, Intializing Fields say (in part),
The Java compiler copies the initialization blocks into each constructor. Therefore, this approach can be used to share a block of code between multiple constructors.
source to share