Junior — Middle
Can you explain the purpose and the working of the constructor in Java?
sobes.tech AI
Answer from AI
In Java, a constructor is a special method of a class that is called when a new object is created. Its main purpose is to initialize the object, that is, to set the initial values of fields.
Features of a constructor:
- The constructor's name matches the class name.
- It has no return type, not even void.
- There can be multiple constructors with different parameters (overloading).
- If a constructor is not explicitly declared, the compiler will create a default constructor without parameters.
Example:
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
When creating an object new Person("Ivan", 30), the constructor that sets the name and age is called.