011-001-003

Self-Introduction Program with Constructor

Medium

Problem Description

📥 Input Format

Read 2 lines from standard input:

  • Line 1: Name (String, no spaces)
  • Line 2: Age (non-negative integer)

📤 Output Format

Name: [name]
Age: [age]

🎯 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)

Reading Input with Scanner

Scanner sc = new Scanner(System.in);
String name = sc.next();  // Read name
int age = sc.nextInt();   // Read age
```java

Use Scanner to read name and age from standard input, then use those values to create a Person object.

### Field Declaration

```java
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. Name and age read via Scanner are passed to `new Person(name, age)`
2. Constructor is executed
3. Parameter name receives the input value
4. Parameter age receives the input value
5. `this.name = name;` assigns the value to field name
6. `this.age = age;` assigns the value 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

## ⚠️ 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

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

## 🔗 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.

Ready to Try Running Code?

Log in to access the code editor and execute your solutions for this problem.

Don't have an account?

Sign Up