3

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 dynamically change when TickMarks change?
When do these variables get initialized?

In particular, public boolean runUpdates = true;. As no initialization is needed because one can call StockGraph.runUpdates to access the variable?

almightyGOSU
  • 3,731
  • 6
  • 31
  • 41
washcloth
  • 2,730
  • 18
  • 29
  • http://stackoverflow.com/questions/1994218/should-i-instantiate-instance-variables-on-declaration-or-in-the-constructor probably the same question – varren Jun 08 '15 at 01:14
  • You cannot call `StockGraph.runUpdates` directly without first creating an instance of StockGraph because this field is not static. – V_Singh Jun 08 '15 at 01:29

2 Answers2

6

What are the properties of these variables?

These are instance variables which are assigned a default value.

Does MiddleTick dynamically change when TickMarks change? When do these variables get initialized?

No MiddleTick will use TickMarks which is available at MiddleTick initialisation time i.e at instance creation time.

in particular public boolean runUpdates = true; As no initialization is needed because one can call StockGraph.runUpdates to access the variable?

runUpdates cannot be directly accessible(StockGraph.runUpdates ) without an instance as it not an instance field and not a static field.

There are different ways to initialise fields in java, depending on the need and code readability. This article throws some light on this:

Initializing Fields in Java

Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
5

Those variables are not initialized prior to calling the constructor, instead they are copied into the constructor(s) immediately after the call to super(). The Java Tutorials, Intializing Fields says (in part),

The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249