I'm seeing what appears to my novice eyes as conflicting conventions in Java, when it comes to declaring instance variables. For example, a classic bank account instance variable might look like this, which makes perfect sense.
private double balance = 0.0;
An access modifier, data type, variable name, and a value are all I (mistakenly) thought went into an instance variable. Now the confusing part.
Consider a library/class/package that is imported, named ColorImage. It apparently has a canvas object, but here's what the instance variable declarations look like.
private Canvas canvas = new Canvas();
private ColorImage image1 = new ColorImage("file.gif");
Now it looks like object names, and even the name of the library/package/class itself, are being used as data types. Moreover, the instance variables have been joined to what look like constructors.
My question: Why is this second syntax ok when it looks like it deviates wildly from the first?
Any help would be appreciated.
Why is this second syntax ok when it looks like it deviates wildly from the first?
It doesn't deviate at all from the first.
Part First example Second example
Access modifier private private
Type double Canvas
Name balance canvas
Initialization expression 0.0 new Canvas()
Where do you see the discrepancy? Yes, the type can be a class, not just a primitive. Yes, the initialization expression can be any expression (that doesn't use other instance variables) not just a literal. That doesn't change the syntax at all.
Note that the access modifier is optional (defaulting to "package access"), and there are other potential modifiers (volatile
, final
, static
). But in your examples, the set of modifiers applied is exactly the same.
See more on this question at Stackoverflow