Commit a7b0e71
committed
feat(constructors): add example demonstrating parameterized constructor and instance initialization
What
- Introduced `Constructors` class with two instance attributes:
- `label` (String) to represent a descriptive identifier.
- `number` (double) to represent a numeric value.
- Implemented a parameterized constructor:
- Accepts `valueOfLabel` and `valueOfNumber` as arguments.
- Initializes `label` and `number` fields at the time of object creation.
- Added `main` method:
- Creates an instance `thing = new Constructors("HIS", 1.2)`.
- Prints the assigned label using `System.out.println`.
Why
- Demonstrates how Java constructors provide a way to initialize objects at creation.
- Reinforces the distinction between **constructors** and **methods**:
- Constructor has the same name as the class, no return type.
- Automatically invoked when an object is created.
- Encourages writing constructors for encapsulating initialization logic instead of using setter methods later.
Logic
1. Fields declared: `label` and `number`.
2. Constructor `Constructors(String, double)`:
- Binds the incoming arguments to the instance attributes.
3. Inside `main`:
- `new Constructors("HIS", 1.2)` allocates memory and calls the constructor.
- Constructor assigns `"HIS"` to `label` and `1.2` to `number`.
- `thing.label` prints `"HIS"`.
Real-life applications
- Parameterized constructors are widely used to ensure **valid state** of objects at creation:
- Example: Creating `User(name, email)` ensures a user always has required info.
- Example: Creating `BankAccount(accountNo, balance)` enforces initialization rules.
- Reduces risk of uninitialized objects and enforces **immutability** when combined with `final` fields.
Notes
- If no constructor is defined, Java provides a default no-arg constructor.
- Once a parameterized constructor is defined, the default constructor is no longer provided unless explicitly added.
- Good practice: use constructors for mandatory fields, setters for optional ones.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 1c71d02 commit a7b0e71
File tree
1 file changed
+5
-9
lines changed- Java 8 Crash Course/Functional Interface/Static Methods/src
1 file changed
+5
-9
lines changedLines changed: 5 additions & 9 deletions
| 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 | | - | |
| 12 | + | |
16 | 13 | | |
17 | 14 | | |
18 | 15 | | |
19 | | - | |
20 | 16 | | |
21 | 17 | | |
22 | 18 | | |
0 commit comments