The basic meaning of Constructor is making or building something and Destructor means destroying or releasing something. So, technically, Constructor allocates memory to the variables for specific instance which have been created at any point in time. On the other hand, Destructor deallocates memory or releases the memory after work has been done.
If you remember or read the first chapter, I have mentioned that JAVA is a Robust Language as it handles both Memory Management Mistakes and Runtime Errors.
Related Links:
- Basic Java – 1 || Understand Java before start learning JAVA.
- Basic Java – 2 || Variables and Data Types used in JAVA.
- Basic Java – 3 || Understanding Class, Objects, Methods in Java.
- Basic Java – 4 || More on methods(Return Type and Parameters)
- Basic Java – 5 || Methods- Call by Value and Call by Reference in Java.
- Basic Java – 6 || Understanding of Constructor and Destructor in JAVA.
- Basic Java – 7 || Static Variables and Methods.
- Basic Java – 8 || Lets learn about Arrays in Java.
- Basic Java – 9 || Performing multiple operations using Java Operators.
- Basic Java – 10 || Conditions (If and Switch) in JAVA.
- Basic Java – 11 || for and for-each in Java. (Loops Part-1)
- Basic Java – 12 || Alternate looping concepts while and do-while. (Loops Part-2)
- Basic Java – 13 || Decimal values v/s Octal base(8) values in JAVA.
- Basic Java – 14 || Learn about String literals in Java.
- Basic Java – 15 || Runtime User Input using Scanner Class (Part-1).
- Basic Java – 16 || Runtime User Input using BufferedReader Class (Part-2).
- Basic Java – 17 || Runtime User Input using Console Class (Part-3).
- Basic Java – 18 || Difference between break and continue keywords.
- Basic Java – 19 || Sending Email using Java (Part-1).
- Basic Java – 20 || Sending Email with attachment using Java (Part-2).
- Basic Java – 21 || Stack memory and Heap memory in Java.
- Basic Java – 22 || Let’s learn more about String.
- Basic Java – 23 || String, StringBuffer & StringBuilder in Java.
- Basic Java – 24 || Exception Handling using Try Catch.
- QnA || How to use Constructors in Abstract class?
- QnA | Difference between Integer and int keywords.
- QnA | Can main method be overloaded?
- QnA | How do I reverse a String/Sentence in Java?
- QnA | Perform Multiplication and Division without * or / or % operators.
- QnA | How do I get the default value of data type?
- QnA | How to split String if it contains period symbol (.) in between?
Constructor
In general, constructors are used for initializing variables as per the user requirement while creation of an Object and allocates memory to that variable while creation of Objects. If we do not define any constructor JAVA calls default constructor at compile time. The constructor is a method which is called at the time of creation of the object. The same constructor will be called each time we create a new object or instance of a class.
Rules for Constructor
- Should have the same name as Class.
- Can have zero or more parameters.
- Shouldn’t have any return type.
- Constructors can not be Overridden Overriding means what we have declared in Superclass, that exactly we have to implement in Subclass.
- Constructors can be Overloaded
- Only default Constructor can be Inherit using Inheritance.
- Constructors can call other methods in it.
Types of Constructor
- Default Constructor, initializes all the variables with default values according to the data type. This constructor can be called automatically at the time of creation of class Object. The default constructor doesn’t have any parameter. We don’t have to create/define the default constructor.
ConstructorTypes obj=new ConstructorTypes();
We can also, define the constructor without any parameter to achieve some specific task.
2. Parameterized Constructor, sometimes we want to initialize object variables with user-defined values at that time we have to create and use the parameterized constructor.
Default Constructor:
package constructorExample; public class ConstructorTypes { int rollNo; String userName; public static void main(String[] args) { // Creating object using default Constructor ConstructorTypes obj=new ConstructorTypes(); System.out.println("Example of Default Constructor:"); System.out.println("Roll No.: "+obj.rollNo); System.out.println("UserName: "+obj.userName); } } Output: Example of Default Constructor: Roll No.: 0 UserName: null
Parameterized Constructor
package constructorExample; public class ParameterizedConstructor { int rollNo; String userName; public static void main(String[] args) { // Passing parameters while creating an object of Class. ParameterizedConstructor obj=new ParameterizedConstructor(4, "Alexgendar"); System.out.println("Roll No.: "+obj.rollNo); System.out.println("UserName: "+obj.userName); } ParameterizedConstructor(int roll, String name) { // Initializing variables with user defined values. rollNo=roll; userName=name; } } Output: Roll No.: 4 UserName: Alexgendar
Constructor Overloading
package constructorExample; public class CosntructorOverloading { int rollNo; String userName; public static void main(String[] args) { // Calling Constructor without any Parameter CosntructorOverloading obj1=new CosntructorOverloading(); System.out.println("Initializing variables with default values:"); System.out.println("Roll No.: "+obj1.rollNo); System.out.println("UserName: "+obj1.userName); // Calling Constructor with Parameters CosntructorOverloading obj2=new CosntructorOverloading(4, "AllinOneBlogs"); System.out.println("\nInitializing variables with user defined values:"); System.out.println("Roll No.: "+obj2.rollNo); System.out.println("UserName: "+obj2.userName); } CosntructorOverloading() { // Initializing variables with default values. rollNo=1; userName="Indian"; } CosntructorOverloading(int roll, String name) { // Initializing variables with user defined values. rollNo=roll; userName=name; } } Output: Initializing variables with default values: Roll No.: 1 UserName: Indian Initializing variables with user defined values: Roll No.: 4 UserName: AllinOneBlogs
Important Note
We can not declare and handle return type of a Constructor method. But each constructor returns a value of that Class type.
TestClass obj=new TestClass();
We can see the second part of the above statement new TestClass(); returns a value which can be stored in an object variable TestClass obj of same Class type.
Destructors
When the purpose of an object gets over, JVM automatically releases the memory for all the variables related to a specific instance. In Java, destructors have been called automatically, we don’t have to call them manually.
Difference Between Constructor and Methods
S.No | Java Constructor | Java Method |
1 | A constructor is used to initialize the variables of a Class. | A method is used to define the behavior/functionalities of an object. |
2 | A constructor must not have a return type. | The method may or may not have a return type. |
3 | The constructor has invoked automatically at the time of object creation. Constructors can be called explicitly when there are multiple constructors are defined. | The method is invoked explicitly using the dot operator. |
4 | The java compiler provides a default constructor if you don’t have any constructor. | There is no existence of default Method. |
5 | Constructor name must be same as the class name. | Method name may or may not be same as class name. |