Commit 8e97ae0
committed
feat: Demonstrate object attributes with multiple instances of Attributes class
WHAT the code does:
- Defines class Attributes with two private instance variables:
- int number
- String word
- In main():
- Creates two separate objects (object1 and object2).
- Assigns different values to each object’s fields.
- Prints selected attributes from each object to show independence.
WHY this matters:
- Shows how **objects in Java maintain their own copies of instance variables**.
- Reinforces the difference between:
- Class-level (static) variables: shared across all instances.
- Instance variables: unique per object.
- Demonstrates encapsulation in theory (though fields are directly accessed here).
- Clarifies how multiple objects of the same class can hold different states.
HOW it works:
1. object1 is created:
- object1.number = 9
- object1.word = "Grade"
2. object2 is created:
- object2.number = 2022
- object2.word = "Java"
3. Printing:
- object1 prints its number (9).
- object2 prints its word ("Java").
- Shows object independence: changing object2 does not affect object1.
Tips and gotchas:
- Fields are declared private but accessed directly in main() because it’s inside the same class.
- Outside this class, direct access is not possible — you’d need getters and setters.
- Prefer using constructors or setter methods to initialize attributes for better encapsulation.
- Overriding toString() could simplify printing object state (e.g., `System.out.println(object1);`).
- Avoid hardcoding values directly into fields; encapsulation is a better practice.
Use-cases / analogies:
- Think of a class as a blueprint (like a form), and objects as filled-in forms.
- object1’s form: number=9, word="Grade".
- object2’s form: number=2022, word="Java".
- Real-world analogy: two smartphones of the same model, but one has different wallpaper and storage space used — same class, different state.
Short key: java-oop object-attributes instance-variables encapsulation object-independence.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 7bb2c6b commit 8e97ae0
1 file changed
+8
-9
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | | - | |
2 | | - | |
| 1 | + | |
3 | 2 | | |
4 | 3 | | |
5 | 4 | | |
6 | | - | |
7 | | - | |
8 | | - | |
| 5 | + | |
| 6 | + | |
9 | 7 | | |
10 | | - | |
| 8 | + | |
| 9 | + | |
11 | 10 | | |
12 | 11 | | |
13 | 12 | | |
14 | | - | |
| 13 | + | |
15 | 14 | | |
16 | 15 | | |
17 | 16 | | |
18 | 17 | | |
19 | | - | |
| 18 | + | |
20 | 19 | | |
21 | 20 | | |
22 | 21 | | |
23 | | - | |
| 22 | + | |
0 commit comments