Categories: Java

More about Constructors

Let us take a look at various other constructors in Java.

Copy constructor:

A copy constructor is a type of constructor in Java that creates an object by copying another object from the same Java class. It returns a copy of a class object that already exists.

If we want to, we can use the copy constructor:

  • Make a duplicate of an object with multiple fields.
  • Make a deep duplicate of the heavy objects.
  • Use the Object.clone() method rarely.
Example:
public class Student
{  
private double fpercent;  
private String fname;  
//constructor to initialize roll number and name of the student  
Student(double fPercent, String fName)  
{   
fpercent = fPercent;  
fname = fName;  
}  
//creating a copy constructor  
Student(Student student)  
{  
System.out.println("\nAfter invoking the Copy Constructor:\n");  
fpercent = student.fpercent;  
fname = student.fname;  
}  
//creating a method that returns the price of the fruit  
double showPercent()  
{  
return fpercent;  
}  
//creating a method that returns the name of the fruit  
String showName()  
{  
return fname;  
}  
//class to create student object and print roll number and name of the student  
public static void main(String args[])  
{  
Student s1 = new Student(91, "Rabecca Fatima");  
System.out.println("Name of the first student: "+ s1.showName());  
System.out.println("Percentage of the first student: "+ s1.showPercent());  
//passing the parameters to the copy constructor  
Student s2 = new Student(s1);
System.out.println("Name of the second student: "+ s2.showName());  
System.out.println("Price of the second student: "+ s2.showPercent());  
}  
}  
Output:
Name of the first student: Rabecca Fatima
Percentage of the first student: 91.0

After invoking the Copy Constructor:

Name of the second student: Rabecca Fatima
Price of the second student: 91.0
Difference between constructor and method in Java:
Java ConstructorJava Method
An object’s state is initialized using a constructor.A method is used to expose an object’s behaviour.
A return type cannot be used in a constructor.A method must have a return type.
The constructor is invoked implicitly.The method is invoked explicitly.
If a class lacks a constructor, the Java compiler provides a default constructor.The compiler does not provide the method in any case.
The constructor name must be the same as the class name.The method name may or may not be the same as the class name.
Constructor Chaining:

Constructor chaining is the process of calling a constructor from another constructor in the same class. It happens because of inheritance. When we create a derived class instance, all the constructors of the inherited class (base class) are called first, followed by the constructor of the calling class (derived class).

There are two ways to achieve constructor chaining:

  • Within a single class: We use this if the constructors are from the same class.
  • From the foundation class: We use the super keyword to call the constructor from the base class if the constructor belongs to different classes (parent and child classes).
Example:
public class ConstructorChain  
{  
//default constructor  
ConstructorChain()  
{  
this("Coderzpy");  
System.out.println("Default coA copy constructor is a type of constructor instructor called.");  
}  
//parameterized constructor  
ConstructorChain(String str)  
{  
System.out.println("Parameterized constructor called");  
}  
//main method  
public static void main(String args[])   
{   
//initializes the instance of example class  
ConstructorChain cc = new ConstructorChain();   
}   
}   
Output:
Parameterized constructor called
Default constructor called.

We created an instance of the class in the preceding example without passing any parameters. Because of this, it first calls the default constructor, which then redirects the call to the parameterized constructor. The parameterized constructor’s statements are executed before returning to the default constructor. The rest of the default constructor statements are then executed, and the object is successfully initialized.

Note: also read about the Constructor in Java

Follow Me

If you like my post please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Share
Published by
Rabecca Fatima

Recent Posts

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

2 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

1 year ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

1 year ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

1 year ago