Java术语Declaration、Initialisation、Instantiation的示例理解是否正确?
Great job breaking down these core Java concepts—let’s confirm each point and add a little extra context to solidify things:
Declaration:
int x;
This is exactly right. Declaration tells the compiler about a variable’s type (int) and name (x) without assigning any value. The variable exists in scope but hasn’t been given a usable state yet.Initialisation:
x = 0;
Correct! Initialisation is the act of assigning a concrete value to a previously declared variable. This gives the variable a valid state it can be used in.Instantiation:
Night n = new Night();
Perfect. Instantiation specifically refers to creating a new instance of a class using thenewkeyword. This step allocates memory for the object, calls its constructor, and returns a reference to the new object. Note that this line combines three actions (declaration, instantiation, initialisation), but thenew Night()part is the instantiation itself.Combined Declaration + Initialisation:
int x = 0;
Yep, this is a standard, valid shorthand. It wraps declaring the variable and setting its initial value into one line—functionally identical to writing the two separate lines you mentioned.Combined Instantiation + Initialisation:
b = new JButton("this is a button");
Assumingbwas already declared (likeJButton b;earlier), this line is completely correct. Here,new JButton("this is a button")instantiates the JButton object, and assigning it tobinitialises the variable to reference that new instance. This merges the instantiation step with the variable’s initialisation.
One tiny extra note: When you write Night n = new Night();, you’re actually performing all three actions in one go—declaring n, instantiating the Night object, and initialising n with that object reference. But your breakdown of each individual term is exactly accurate.
内容的提问来源于stack exchange,提问作者Jashan

