NewGuy_IL
NewGuy_IL

Reputation: 51

Instance Variable Declaration Syntax

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.

Upvotes: 3

Views: 432

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1503599

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.

Upvotes: 5

Anderson Vieira
Anderson Vieira

Reputation: 9059

An access modifier, data type, variable name, and a value are all I (mistakenly) thought went into an instance variable

It's actually the same:

private ColorImage image1 = new ColorImage("file.gif");

private - access modifier
ColorImage - data type
image1 - variable name
new ColorImage("file.gif") - expression that creates a new object and returns the value of the object reference

Java data types can be primitive types or reference types. In your example, double is a primitive type, and ColorImage and Canvas are both reference types.

To the right side of the = you could have any expression:

private double balance = 1.0 - 1.0;

or

private double balance = zero();
static double zero() {
    return 0.0;
}

Upvotes: 3

Related Questions