constructor in java
In Java, a constructor is a special type of method that is automatically called when an object of a class is created. It is used to initialize the newly created object and can perform tasks such as setting initial values for instance variables or executing any necessary setup logic. Here are some key aspects of constructors in Java:
Table of Contents
- 1. Name: Constructors have the same name as the class in which they are defined.
- 2. No Return Type: Constructors do not have a return type, not even ‘void’. This is because they are automatically called when an object is created and cannot return a value.
- 3. Purpose: The primary purpose of a constructor is to initialize the state of an object by setting initial values to its instance variables or performing any necessary setup tasks.
- 4. Automatic Invocation: Constructors are automatically invoked when an object of the class is created using the ‘new’ keyword.
- 5. Overloading: Like other methods, constructors can be overloaded, meaning that a class can have multiple constructors with different parameter lists. This allows objects to be initialized in different ways.
- 6. Default Constructor: If a class does not explicitly define any constructors, Java provides a default constructor with no parameters. This default constructor initializes instance variables to their default values (e.g., ‘0’ for numeric types, ‘null’ for object references).
- 7. Initialization Order: Constructors are called in a specific order during object creation. If a subclass constructor is called, it must first invoke a constructor of its superclass using ‘super()’.
- 8. Visibility: Constructors can have different access modifiers (‘public’, ‘private’, ‘protected’, or default) to control their visibility and accessibility.
- 9. Implicit Superclass Constructor Call: If a subclass constructor does not explicitly call a superclass constructor using super(), Java automatically inserts a call to the superclass’s no-argument constructor.
Example of a class with a constructor
public class Car {
private String make;
private String model;
private int year;
// Constructor with parameters
public Car(String make, String model, int year) {
this.make = make;
this.model = model;
this.year = year;
}
// Getter methods (not shown for brevity)
}
In this example, the ‘Car’ class has a constructor that takes three parameters (‘make’, ‘model’, and ‘year’). When a ‘Car’ object is created, this constructor is automatically called to initialize its state with the provided values.