How is the constructor in Java called?

In Java, a constructor is a special method used to create objects that is automatically called when the object is created. The constructor is invoked by using the keyword “new”.

When calling the constructor method, the following steps need to be followed:

  1. fresh
  2. Create a new instance of the ClassName class and assign it to the objectName variable.
  3. I need to finish my homework before dinner.
  4. Create a new object of the class ClassName and name it objectName.

Important Notes:

  1. The name of the constructor must be identical to the class name.
  2. Constructor methods do not have a return type, so there is no need to use the void keyword to declare a return type.
  3. If no constructor is defined, a default parameterless constructor will be provided by default.
  4. If one or more constructors are defined in a class, the appropriate constructor method must be selected and called based on the types and number of parameters when creating an object.

Here is an example demonstrating how to call a constructor:

public class Person {
    private String name;
    private int age;
    
    // 无参构造方法
    public Person() {
        name = "John";
        age = 30;
    }
    
    // 有参构造方法
    public Person(String n, int a) {
        name = n;
        age = a;
    }
    
    public String getName() {
        return name;
    }
    
    public int getAge() {
        return age;
    }
    
    public static void main(String[] args) {
        // 调用无参构造方法
        Person person1 = new Person();
        System.out.println("Name: " + person1.getName());
        System.out.println("Age: " + person1.getAge());
        
        // 调用有参构造方法
        Person person2 = new Person("Tom", 25);
        System.out.println("Name: " + person2.getName());
        System.out.println("Age: " + person2.getAge());
    }
}

The output result is:

Name: John
Age: 30
Name: Tom
Age: 25
bannerAds