Basic Java – 6 || Understanding of Constructor and Destructor in JAVA.

            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:

OOPs Concept:

Java Question And Answer:

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.

Constructor

Rules for Constructor

  1. Should have the same name as Class.
  2. Can have zero or more parameters.
  3. Shouldn’t have any return type.
  4. Constructors can not be Overridden Overriding means what we have declared in Superclass, that exactly we have to implement in Subclass.
  5. Constructors can be Overloaded
  6. Only default Constructor can be Inherit using Inheritance.
  7. Constructors can call other methods in it.

Types of Constructor

  1. 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.

3060total visits,3visits today

Leave a Reply

Your email address will not be published. Required fields are marked *