Commit 9954233
committed
feat: Add Practice and A classes to demonstrate instance fields with add and mul methods
WHAT the code does:
Defines class A with instance fields x, y, sum, and res.
add(int x, int y) assigns arguments to instance fields using this, computes their sum, and prints it.
mul() multiplies the stored instance fields and prints the result.
Defines a Practice class with main() that:
- Creates an object of A
- Calls add(5, 7) to compute and print 12
- Calls mul() to compute and print 35
WHY this matters:
Demonstrates how instance fields retain values across method calls in the same object.
Shows the use of the this keyword to distinguish between method parameters and instance variables.
Highlights a basic form of object state: results from one method (add) persist for use in another method (mul).
Introduces a foundational concept for object-oriented programming: encapsulating behavior (methods) with data (fields).
HOW it works:
In main(), an A object is created.
add(5, 7) sets x = 5, y = 7, computes sum = 12, and prints 12.
mul() then multiplies the stored x and y → 5 * 7 = 35, and prints 35.
Because x and y were stored as instance fields, mul() could use them without requiring arguments.
Tips and gotchas:
Relying on mutable instance fields can make objects harder to reason about; consider returning values instead of printing directly.
Better design would compute results and return them, letting main() decide how to use or print values.
In larger designs, separating computation logic from I/O improves testability and reuse.
Using constructors instead of setter-style methods (like add) could make object initialization more explicit.
Use-cases:
Educational demonstration of instance variables and method chaining.
Introductory example of how object state persists across method calls.
Foundation for more complex classes where multiple operations depend on shared internal state.
Short key: class-practice object-state this-keyword add-mul.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 678da37 commit 9954233
1 file changed
+7
-11
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | | - | |
2 | | - | |
3 | | - | |
4 | | - | |
| 1 | + | |
| 2 | + | |
5 | 3 | | |
6 | 4 | | |
7 | 5 | | |
8 | 6 | | |
9 | 7 | | |
10 | | - | |
11 | | - | |
| 8 | + | |
12 | 9 | | |
13 | | - | |
14 | | - | |
| 10 | + | |
| 11 | + | |
15 | 12 | | |
16 | 13 | | |
17 | 14 | | |
18 | 15 | | |
19 | 16 | | |
20 | | - | |
21 | | - | |
| 17 | + | |
22 | 18 | | |
23 | 19 | | |
24 | 20 | | |
25 | | - | |
| 21 | + | |
0 commit comments