Object Creation and Storage
| English | Chinese | Pinyin |
|---|---|---|
| constructor | 构造函数 | gòu zào hán shù |
| instantiation | 实例化 | shí lì huà |
Making a new object
- To create an object, use the
newkeyword and a constructor 构造函数. Scanner sc = new Scanner(System.in);builds a fresh Scanner object.- Instantiation 实例化 is the act of creating an object from a class.
- The constructor sets up the object's starting state.
Constructor arguments
- A constructor can take arguments to configure the new object.
new Random(42)seeds a random generator;new String("hi")copies text.- The arguments match the constructor's parameters, by position and type.
- Different constructors (overloaded) let you build the same class different ways.
Storing the reference
newreturns a reference to the object; store it in a variable of the right type.Scanner sc = new Scanner(System.in);—scnow refers to that object.- The object lives in memory;
scis just the label pointing at it. - Lose the reference (no variable holds it) and the object becomes unreachable.
Two variables, one object
- Assigning one object variable to another copies the reference, not the object.
Scanner sc2 = sc;— nowscandsc2point to the same Scanner.- A change through
sc2is visible throughsc— it's one object. - This reference-copy behavior is a defining feature (and trap) of objects.
new creates ONE object and hands back a reference to it. Assigning that variable to another (b = a;) copies the reference, so both names point to the same object — not a second copy. Contrast primitives (int y = x; copies the value). Forgetting this leads to "I changed b, why did a change too?" surprises.
Instantiation and aliasing:
Random r = new Random();→rrefers to a new Random object.Random r2 = r;→r2points at the same object (no new object made).- Both
randr2now share one generator's state.
Create an object with new plus a constructor (instantiation): new Scanner(System.in). new returns a reference you store in a variable. Assigning one object variable to another copies the reference — both then refer to the same object (unlike primitives, which copy the value).
new makes one object; = copies the reference
r and r2 share one object; x and y are independent copies.
Which keyword creates a new object?
new plus a constructor instantiates an object.
The special method called to build a new object is a ___ (one word).
The constructor sets up the new object.
After Random r2 = r; how many Random objects exist?
Assigning copies the reference, not the object — still one object.
Assigning one object variable to another (b = a) makes a second, independent object.
It copies the reference — both point to the same object.
For primitives, int y = x; copies the value, so x and y are independent.
Primitives copy the value; objects copy the reference.