Java Constructor

In Java, constructors are special methods used to create objects of a class.

When an object is created using the `new` keyword, the constructor is automatically called to initialize the object's attributes.

Constructors have the following characteristics:

  • Same name as the class: The constructor's name must exactly match the class name, including capitalization. This is a basic requirement for constructors.

  • No return type: Constructors have no return type declaration, evenvoid`void` is not written. This distinguishes them from ordinary methods.

  • Automatic invocation: Every timenew`new` is used to create an object, the constructor is automatically invoked to initialize the object's attributes and state.

  • Cannot be called directly: Constructors can only be called through thenew`new` keyword when creating an object; they cannot be called directly like ordinary methods.

  • Supports overloading: You can define multiple constructors for a class as long as their parameter lists are different. Through overloading, different constructors can be created to meet different initialization needs.

  • Default constructor: If no constructor is defined, Java provides a no-argument default constructor. But once any other constructor is defined, Java no longer provides the default constructor.

  • thisUse of the `this` Keyword: In constructors, you can use `this`thisto refer to the current object's attributes and methods, or to call another constructor (must be the first line of the constructor), to avoid duplicate code.

  • Cannot be inherited, but can be called: Constructors cannot be inherited by subclasses, but subclasses can use `super`super()to call the parent class constructor, in order to initialize inherited attributes.

  • Object initialization guarantee: The main function of a constructor is to initialize the object's attributes and state, ensuring that the object is in a valid initial state when created.

The role of constructors:

  • Initialize object attributes: The main role of a constructor is to assign initial values to object attributes.
  • Ensure completeness of object initialization: In constructors, you can set default values or required parameters to avoid the problem of incomplete object initialization.

Types of Constructors

Constructors in Java are divided into two types:No-argument constructorandParameterized constructor。

1. No-Argument Constructor (Default Constructor)

If a class has no constructor defined, Java provides a no-argument constructor by default. For example:

Example

public class Person {
    public Person() {
        System.out.println("Person object created");
    }
}
  • When no constructor is explicitly defined, Java automatically provides a default no-argument constructor.
  • Once any other constructor is defined, Java will no longer provide the default constructor.

2. Parameterized Constructor

You can define constructors with parameters to assign values to attributes when creating objects:

Example

public class Person {
    String name;
    int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

When calling a parameterized constructor, you can initialize the object's attributes:

Person p = new Person("Alice", 25);

Constructor Overloading

Java supports constructor overloading, meaning you can define multiple constructors in the same class as long as the parameter lists are different. For example:

Example

public class Person {
    String name;
    int age;

    public Person() {
        this.name = "Unknown";
        this.age = 0;
    }

    public Person(String name) {
        this.name = name;
        this.age = 0;
    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

When creating an object, Java automatically chooses the matching constructor based on the number and type of arguments passed:

Person p1 = new Person(); // 调用无参构造方法
Person p2 = new Person("Alice"); // 调用单参数构造方法
Person p3 = new Person("Bob", 30); // 调用双参数构造方法

The this Keyword in Constructors

In constructors, the `this` keyword is usually used in two cases:

1. Refer to the current object's attributes or methods:When the parameter names of a constructor are the same as the class attribute names, use `this` to distinguish class attributes from parameters. For example:

Example

public Person(String name, int age) {
    this.name = name; // this.name refers to the class attribute
    this.age = age;
}

2. Call another constructor:You can use `this()` to call another constructor of the current class. It is often used to avoid duplicate code, but it must be placed on the first line of the constructor.

Example

public Person(String name) {
    this(name, 0); // Call another two-parameter constructor
}

public Person(String name, int age) {
    this.name = name;
    this.age = age;
}

Constructors are a very important part of Java object-oriented programming. Through constructors, you can effectively control the object initialization process and ensure the integrity and consistency of the created object's state.

Other extensions