Self-Introduction Program with Constructor
Problem Description
🎯 Problem Overview
In this problem, you will learn about "constructors," which are fundamental to Java's object-oriented programming. A constructor is a special method that is automatically called when an object is created, and it is used to set the initial state of the object.
In real-world applications, constructors are frequently used when converting user information retrieved from a database into objects or treating configuration file contents as objects. Understanding this foundation will enable you to progress to more complex program design.
📚 Prerequisites
What is a class?
A class is like a "blueprint." For example, when building a house, the blueprint is the "class," and the actual built house is the "object." From the Person class blueprint, you can create specific people (objects) like Alice or Bob.
What are Fields?
Fields are the data that an object holds. In the case of the Person class, name and age are fields. These are marked with the private access modifier to prevent direct access from outside (encapsulation).
Role of Constructor
A constructor performs the initialization process required when creating an object. For example, it can enforce the rule that when creating a Person object, you must always set the name and age.
📖 Code Explanation (Step by Step)
Field Declaration
private String name;
private int age;
```java
These two lines define the data (fields) that the Person class holds.
- `private`: This field cannot be accessed directly from outside. It can only be used inside the class.
- `String name`: Declares a String <a href="https://javadrill.tech/problems/001">variable</a> name to store a person's name.
- `int age`: Declares an int variable age to store a person's age.
At this point, these variables are only declared and have no values (null or 0).
### Constructor Definition
```java
public Person(String name, int age) {
```java
Constructor characteristics:
- Exactly the same name as the class name (Person)
- No return type (not even void)
- `public` allows it to be called from outside as `new Person(...)`
- Receives data needed for initialization (name and age) as arguments
### Using the this Keyword
```java
this.name = name;
this.age = age;
```java
`this` is a keyword that refers to "this object itself."
- `this.name`: The name field of this object
- `name`: The name passed as an argument to the constructor
Why is `this` necessary?
When the field name and parameter name are the same, you cannot distinguish which one you are referring to without `this`. By writing `this.name = name;`, you clearly distinguish "left side is field, right side is parameter."
Execution flow:
1. `new Person("Alice", 25)` is called
2. Constructor is executed
3. Parameter name receives "Alice"
4. Parameter age receives 25
5. `this.name = name;` assigns "Alice" to field name
6. `this.age = age;` assigns 25 to field age
7. Object initialization is complete
### introduce Method Implementation
```java
public String introduce() {
return "Name: " + name + "\nAge: " + age;
}
```java
This method:
- Has return type String (returns a string)
- Has no arguments (only uses field values)
- Concatenates strings using the `+` <a href="https://javadrill.tech/problems/003">operator</a>
- `\n` is an escape sequence representing newline
Execution example:
- When name field is "Alice" and age field is 25
- "Name: " + "Alice" + "\n" + "Age: " + 25
- Result: "Name: Alice\nAge: 25" (2-line string)
## ⚠️ Common Mistakes
### 1. Writing Return Type for Constructor
Wrong example:
```java
public void Person(String name, int age) { // ❌ void is unnecessary
this.name = name;
this.age = age;
}
```java
Reason: Constructor does not have a return type. Writing void makes this a regular method, not a constructor.
Correct approach:
```java
public Person(String name, int age) { // ✅ No return type
this.name = name;
this.age = age;
}
```java
### 2. Assigning to Field Without this
Wrong example:
```java
public Person(String name, int age) {
name = name; // ❌ Nothing happens
age = age; // ❌ Nothing happens
}
```java
Reason: Writing `name = name;` just assigns parameter name to parameter name, nothing is assigned to the field. The field value remains null or 0.
Correct approach:
```java
public Person(String name, int age) {
this.name = name; // ✅ Assign to field
this.age = age; // ✅ Assign to field
}
```java
### 3. Forgetting to Declare Fields
Wrong example:
```java
public class Person {
// ❌ No fields
public Person(String name, int age) {
this.name = name; // Error: name field does not exist
this.age = age; // Error: age field does not exist
}
}
```java
Reason: You need to declare fields before assigning in constructor.
Correct approach:
```java
public class Person {
private String name; // ✅ Field declaration
private int age; // ✅ Field declaration
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
```java
## 🚀 Advanced Topics
### Multiple Constructors (Overloading)
You can define multiple constructors in one class:
```java
public class Person {
private String name;
private int age;
// Constructor 1: Specify name and age
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Constructor 2: Specify name only (age defaults to 0)
public Person(String name) {
this.name = name;
this.age = 0;
}
// Constructor 3: No arguments (set default values)
public Person() {
this.name = "Unknown";
this.age = 0;
}
}
```java
### Constructor with Input Validation
In practice, constructors perform validation to reject invalid values:
```java
public Person(String name, int age) {
if (name == null || name.isEmpty()) {
throw new IllegalArgumentException("Name cannot be empty");
}
if (age < 0) {
throw new IllegalArgumentException("Age must be positive");
}
this.name = name;
this.age = age;
}
```java
### Adding Getter Methods
When fields are private, it's common to provide getter methods to retrieve values:
```java
public String getName() {
return name;
}
public int getAge() {
return age;
}
```java
## 🔗 Related Learning Topics
- **Encapsulation** (Category 008): Design pattern using private fields and getter/setter methods
- **<a href="https://javadrill.tech/problems/010">method overloading</a>** (Category 012): Defining multiple methods with same name but different parameters
- **Class <a href="https://javadrill.tech/problems/014">inheritance</a>** (Category 015): Creating new classes based on existing classes
- **<a href="https://javadrill.tech/problems/019/001">exception handling</a>** (Category 019): Throwing errors for invalid input.
Test Cases
※ Output examples follow programming industry standards
Name: Alice Age: 25
Name: Bob Age: 30
Name: Baby Age: 0
Name: Elder Age: 100
Name: Eve Age: 18
Your Solution
You have 8 free executions remaining
