Java Constructor
2026-03-27 22:44
Tags: #java
Author: Duke Hsu
Key concept
- Constructor is A special method to initialize objects
- You can pass arguments to a constructor and set up initial values
Code Example
Main class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |
FamilyMember class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | |
Constructor in Java - Key Points
The 3 Most Important Things
| Priority | What to Remember | Why It Matters |
|---|---|---|
| Most Important | Constructor name MUST match the class name exactly | Same spelling, same capital letters. If you get it wrong, Java won't recognize it as a constructor |
| Very Important | Initialize all properties | Make sure every object property gets a value. Don't leave anything empty or with default values |
| Important | Use thisto refer to object properties |
It makes clear which is the property and which is the parameter. Makes your code easier to read |
Before you submit your code, ask yourself these questions:
- [ ] Does the constructor name match the class name exactly (same capital letters)?
- [ ] Did I set a value for every single property?
- [ ] Did I use "this" when assigning values to properties?
- [ ] Did I write "public" in front of the constructor?
- [ ] Are my parameter names clear and easy to understand?
References
Learn CONSTRUCTORS in 10 minutes! - https://www.youtube.com/watch?v=ZD7CB6wKg8A
