Constructor –
- It is similar to a method, has the same name as the class name, but it does not have a return type.
- It gets called automatically when an instance of a class is created.
- When a constructor is called, memory is allocated to an object.
- In addition, if no constructor is present, the compiler will provide a default constructor.
- One can assign values to a class variable within a constructor.
- A constructor cannot be abstract, final, static, or synchronized.
- Access modifiers can be used in the constructor declaration to control which class can call it.
- Types of a constructor –
- No argument constructor –
- A default constructor is a constructor with no arguments.
- If we don’t create a default constructor, the compiler will provide one.
- The default values provided by the default constructor to the object like 0, null, etc.
- Syntax – <class_name>(){}
- Parameterized constructor –
- A constructor with parameters.
- If we want to initialize parameters on our own, use a parameterized constructor.
- Syntax – <class_name>(parameters) { initialize parameters}
- No argument constructor –
//Default Constructor
class Person{
int id;
String name;
void display() {
System.out.println(id + " " + name);
}
public static void main(String args[]) {
//creating object
Person person = new Person();
person.display();
}
}
OUTPUT : 0 null
//Parameterized Constructor
class Person{
int id;
String name;
//parameterized constructor
Person(int i, String n) {
id = i;
name = n;
}
void display() {
System.out.println(id + " " + name);
}
public static void main(String args[]) {
//creating object
Person person = new Person(1, Ram);
person.display();
}
}
OUTPUT : 1 Ram
Destructor –
- It is similar to a method, has the same name as the class name, but it does not have a return type or any parameters.
- When an object destroys, it calls the destructor automatically.
- When a destructor is called, it releases the memory assigned to the object and the resources.
- The finalize method present in the Object class invokes the destructor, but it’s not recommended as it’s not safe.
- There is no syntax for destructors in java because JVM handles it for you using automatic garbage collection.
- So, JVM will keep searching objects whose address is not present in any pointer, and its memory is released.
What are constructors in java?
A constructor is similar to a method, has the same name as the class name but it does not have a return type. It gets called automatically when an instance of a class is created. When a constructor is called, memory is allocated to an object.