Commit 98eb17b
committed
feat: Add ReturningValues class with add and product instance methods
WHAT the code does:
- Defines a `ReturningValues` class with attributes `number1` and `number2`.
- Constructor initializes both attributes.
- `addToNumbers(int a)` increases both numbers by a given value.
- `getProduct()` computes and returns the product of the two numbers.
- `main()` demonstrates:
- Creating an object with values (1, 2).
- Modifying them with `addToNumbers(3)` → numbers become (4, 5).
- Printing updated values.
- Calculating product (4 × 5 = 20) and printing result.
WHY this matters:
- Demonstrates **instance methods vs constructor initialization**.
- Shows **state mutation** of object attributes through methods.
- Introduces returning values from methods instead of only printing.
HOW it works:
1. Constructor assigns `1` and `2` to `number1` and `number2`.
2. `addToNumbers(3)` → adds 3 to each, making them `4` and `5`.
3. `getProduct()` → multiplies updated values → `20`.
4. Results are printed step by step.
Tips & gotchas:
- Fields are package-private (default) → better to make them `private` and use getters for encapsulation.
- Multiple calls to `addToNumbers()` keep incrementing values.
- Using `int` can overflow for very large numbers; `long` or `BigInteger` may be safer.
- `getProduct()` creates a local variable unnecessarily → can directly `return number1 * number2`.
Use-cases:
- Educational example for **methods returning values**.
- Foundation for designing classes that encapsulate arithmetic logic.
- Practice with constructors, instance fields, and mutator methods.
- Can be extended to more complex math operations.
Short key: class-returning values-add-product.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent ac2fd3b commit 98eb17b
1 file changed
+14
-17
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | | - | |
2 | | - | |
3 | | - | |
| 1 | + | |
| 2 | + | |
4 | 3 | | |
5 | 4 | | |
6 | 5 | | |
7 | | - | |
8 | | - | |
9 | | - | |
| 6 | + | |
| 7 | + | |
10 | 8 | | |
11 | 9 | | |
12 | 10 | | |
13 | 11 | | |
14 | | - | |
15 | | - | |
16 | | - | |
| 12 | + | |
| 13 | + | |
17 | 14 | | |
18 | 15 | | |
19 | 16 | | |
20 | 17 | | |
21 | | - | |
22 | | - | |
| 18 | + | |
23 | 19 | | |
24 | 20 | | |
25 | 21 | | |
26 | 22 | | |
27 | | - | |
28 | | - | |
29 | | - | |
| 23 | + | |
| 24 | + | |
30 | 25 | | |
31 | | - | |
| 26 | + | |
| 27 | + | |
32 | 28 | | |
33 | 29 | | |
34 | 30 | | |
35 | | - | |
| 31 | + | |
| 32 | + | |
36 | 33 | | |
37 | 34 | | |
38 | 35 | | |
39 | | - | |
| 36 | + | |
0 commit comments