Object-Oriented Programming Concepts: Constructor & Destructor
In this lecture, i will talk about the Constructors & Destructors in Java.
Table Of Contents
Constructor
A constructor is as special method which is used to initialize objects when creating the object. When we create an object from a class the constructor is called. It is used to set some initial values to the object attributes.
- A constructor can have parameter or it can be empty.
- A constructor is called just after the memory is allocated for the object.
Example
public class ExampleClass {
String name;
public ExampleClass(String name) {
this.name = name;
}
public String getName() {
return name;
}
public static void main(String[] args) {
ExampleClass example = new ExampleClass("Mehadi Hasan");
System.out.println(example.getName());
}
}
Constructor Overloading
We know that methods can be overloaded, in the same way a constructor can also be overloaded. When we have more than one constructor with different parameters we call it constructor overloading. By doing this we can perform different task for each constructor.
Example
public class ExampleClass {
String name;
public ExampleClass() {
this.name = "Default Name";
}
public ExampleClass(String name) {
this.name = name;
}
public String getName() {
return name;
}
public static void main(String[] args) {
ExampleClass def = new ExampleClass();
System.out.println(def.getName());
ExampleClass example = new ExampleClass("Mehadi Hasan");
System.out.println(example.getName());
}
}
Destructor
When the life-cycle of an object is completed a destructor is called. A destructor is also a special method which is called to free the used memory. In Java the destructors are known as finalizers. The allocation and release of memory are implicitly handled by the garbage collector in Java.