Constructors

invisibleufo101·2024년 9월 14일

Java

목록 보기
4/10
post-thumbnail

Initializing Instances with Constructors

The new keyword calls the constructor to set the initial fields for an instance.

When an instance is made, in the stack area, the instance’s name is stored along with a memory address that points to where the actual object is (in the heap area).

Default Constructor

This is created when the declaration of a constructor is skipped. The JVM automatically adds bytecode that adds a constructor to a class if none is declared.

Example:

Car myCar = new Car();  // The constructor method is called

public class Car {
}

The bytecode would generate:

public class Car {
    public Car() {}  // Constructor is automatically added
}

Overloading Constructors

In C++, some STL functions can take different parameters and produce the same results. Overloading is similar: declaring the same method with different parameters.

When overloading constructors, we are able to have multiple constructors in a single class, giving us multiple options to initialize the instance. The number, order, and types of parameters must be different.

Ex)

public class Car {
    public Car() {}

    public Car(String brandName, String modelName) {  // Overloading
        this.brandName = brandName;
        this.modelName = modelName;
    }

    public Car(String model, int maxSpeed) {  // Overloading
        this.model = model;
        this.maxSpeed = maxSpeed;
    }
}

Important Note: Constructors are identified by the number, type, and order of parameters. Therefore, a constructor like this:

public Car(String model, String brandName) {
}

will cause an error if there's already a constructor like Car(String, String) because they share the same number and types of parameters.

Using this()

To reduce redundancy in code (e.g., repeating this.attribute = attribute), we can use this() to call other constructors within the current constructor, allowing us to initialize values more efficiently.

Ex)

public class Car {
    String model;
    String color;
    int maxSpeed;

    public Car(String model) {  // Takes model as parameter, sets color to "Silver" and maxSpeed to 250
        this(model, "Silver", 250);  // Calls another constructor
    }

    public Car(String model, String color) {  // Takes model and color as parameters, sets maxSpeed to 250
        this(model, color, 250);
    }

    public Car(String model, String color, int maxSpeed) {  // Initializes all fields
        this.model = model;
        this.color = color;
        this.maxSpeed = maxSpeed;
    }
}
profile
하나씩 차근차근

0개의 댓글