Instance Variable Declaration Syntax

I see what appears to my newbies as contradictory conventions in Java when it comes to declaring instance variables. For example, a classic bank account instance variable might look like this, which makes sense.

private double balance = 0.0;

      

The access modifier, datatype, variable name, and value are all I (wrongly) thought ended up in an instance variable. Now for the confusing part.

Consider an imported library / class / package named ColorImage. It apparently has a canvas object, but this is 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, which are used as data types. Moreover, instance variables have been chained to constructors that look like constructors.

My question is: Why is this second syntax approved when it seems like it deviates wildly from the first?

Any help would be appreciated.

+3


source to share


2 answers


Why is this second syntax approved when it seems to deviate from the first?

It does not 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, a type can be a class, not just primitive. Yes, an initialization expression can be any expression (that does not use other instance variables), not just a literal. This doesn't change the syntax at all.

Please note that the access modifier is optional (the default is "access package"), but there are also other potential modifiers ( volatile

, final

, static

). But in your examples, the applied modifier set is exactly the same.

+5


source


Access modifier, datatype, variable name and value are all I (wrongly) thought ended up in 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

u Canvas

are reference types.



On the right side, =

you can get any expression:

private double balance = 1.0 - 1.0;

      

or

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

      

+3


source







All Articles