Object Creation
1. Class vs Object (beginner — blueprint vs house!)
Class = blueprint (class Dog { bark(); } — no memory!). Object = built house (new Dog() — Heap memory!). One class → many objects (tommy, moty).
class Dog {
String name;
void bark() { System.out.println(name + " woofs!"); }
}
public class Main {
public static void main(String[] args) {
Dog d1; // 1. declare (null, no house!)
d1 = new Dog(); // 2. new (Heap house + constructor!)
d1.name = "Tommy"; // 3. use (. operator!)
d1.bark(); // Tommy woofs!
Dog d2 = new Dog(); // second house (independent!)
d2.name = "Moty";
d2.bark(); // Moty woofs! (d1 unaffected!)
}
}
4. Traps
Dog d; d.bark();→ NPE (nonew— no house!).d1 = d2;copies address (ONE house, two remotes — like arrays!).newcalls constructor (next topics!) to init.
5. Exam Points
- Class vs object +
newsteps with diagram — 5-7 marks, very frequent. - Two-object independence proof — 3 marks, frequent.