Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Constructors
3.
Default constructor
3.1.
Example
3.2.
Output
3.3.
Explanation
4.
Parameterized Constructors
4.1.
Example
4.2.
Output
4.3.
Explanation
5.
Constructor Overloading
5.1.
Example
5.2.
Output
5.3.
Explanation
6.
FAQs
7.
Key Takeaways
Last Updated: Mar 27, 2024

Constructors

Author Saksham Gupta
3 upvotes

Introduction

When it comes to technical interviews, interviewers frequently focus on functions. The questions are mostly theoretical, and one's understanding of functions should be on point. On the other hand, you do not need to be concerned about any of it. Ninjas are here to help, and today we'll go over one of the most often asked topics about this subject., i.e., Constructors in Java.

Also see about Iteration Statements in Java and Hashcode Method in Java

Constructors

In Java, a constructor is a piece of code similar to a method. This method is called whenever a new instance of the class is created. When the constructor is called, memory for the object is allocated.

It's a specific type of method for configuring an object.

When an object is formed with the new() keyword, at least one constructor is called.

The default constructor is used if no constructor is available in the class. In this case, the Java compiler constructs a default constructor for you.

But how do we declare a constructor?

The following are the rules for writing constructors:

  • A class's constructor(s) must have the same name as the class in which it is found.
  • A constructor can't be abstract, final, static, or synchronous in Java.
  • Access modifiers can be used in constructor declarations to control access to the constructor, i.e., which other classes can call it.
     

How many types of constructors are there?

 

                                                                  Source: source

Also see, Swap Function in Java

Default constructor

When a constructor has no parameters, it is called "Default Constructor."

If we don't define a constructor in a class, the compiler constructs a default constructor for the class (with no arguments). And if we write a  constructor with or without arguments, the compiler does not generate a default constructor.

Let's understand this better by an example.

Example

class CodingNinjas
 {
   /*Default constructor */
   CodingNinjas()
   {
      System.out.println("A new coder is born");
   }

   public static void main(String args[])
   {
      /*Creating a new object and calling default constructor.*/
      CodingNinjas ninja = new CodingNinjas();
   }
 }

Output

A new coder is born.


Note: The default constructor gives the object default values like 0, null, and so on, depending on the type.

Explanation

As soon as the new object is created, the default constructor is called.

Parameterized Constructors

Parameterized constructors are constructors that have parameters. If we wish to set our own values in the class's fields, we should use a parameterized constructor. Let's understand this better by an example.

Example

class CodingNinjas
{
   int ninjaID;
   String name;

   /*Parameterized constructor */
   CodingNinjas(int iD, String n)
   {
      ninjaID = iD;
      name = n;
   }

   /*Display */
   void display()
   {
      System.out.println(ninjaID + " " + name);

   }

   public static void main(String args[])
   {
      /*New object is being created*/
      CodingNinjas ninja = new CodingNinjas(169, "Ankush");
      ninja.display();
   }
}

Output

169 Ankush

Explanation

We passed the ninjaID and name from the parameterized constructor; Thus the variable ‘ninja’ got initialized by the ninjaID 169, and the name 

You can also read about the Multiple Inheritance in Java, Duck Number in Java.

Constructor Overloading

In Java, a constructor is similar to a method, except that it does not return a value. It can be overloaded, just like Java methods.

Constructor overloading is the usage of several constructors with different argument lists in Java. They're organised in such a way that each constructor performs a different function. The number of parameters in the list and their types are used by the compiler to distinguish them.

Let's understand this better by an example.

Example

class CodingNinjas
{
   int ninjaID;
   String name;
   int rating;

   /*Parameterized constructor  */
   CodingNinjas(int iD, String n)
   {
      ninjaID = iD;
      name = n;
   }

   /*Constructor overloading */
   CodingNinjas(int iD, String n, int r)
   {
      ninjaID = iD;
      name = n;
      rating = r;

   }

   /*Display */
   void display()
   {
      System.out.println(ninjaID + " " + name + " " + rating);

   }

   public static void main(String args[])
   {
      /*New objects are being created*/
      CodingNinjas ninja = new CodingNinjas(169, "Ankush");
      CodingNinjas ninja2 = new CodingNinjas(69, "Nidhi", 2002);

      /*Displaying the values */
      ninja.display();
      ninja2.display();

   }
}

Output

169 Ankush 0
69 Nidhi 2002

Explanation

We can see that we have overloaded constructors, and both of them can be distinguished by the number of parameters in them. Ankush is created from the first constructor, and it does not have any value of rating (0 being the default), whereas Nidhi is created with a constructor, which also initializes rating; thus, it's also outputting the rating.

Must Read Conditional Statements in Java

FAQs

  1. Why is Java a platform-independent language?
    Because it does not rely on a platform, Java is platform-independent. Java will now be a platform-agnostic language. Programs are compiled into byte code in Java, which is platform-agnostic. The Java Virtual System is required to run byte code on any machine.
     
  2. Why is Java not a purely object-oriented language?
    Because it supports primitive data types such as int, byte, long, short, and so on, Java is not a fully object-oriented language. As a result, data types such as int, float, double, and others are not object-oriented. As a result, Java is not entirely object-oriented.
     
  3. What is the use of the Java util package?
    It contains the classes needed to make an applet that can communicate with its applet context. It includes all of the classes needed to create user interfaces as well as paint graphics and pictures.
     
  4. Why do we use import Java util.*?
    It means importing all the classes and interfaces within java.util package and making them available within the current class or interface. This is shorthand wild card annotation for importing all classes within a particular package.
     
  5. Is there any other Data Structures and Algorithms content in Coding Ninjas Studio?
    It entails bringing all of the classes and interfaces in the java.util package into the current class or interface. This is a shortcut wildcard annotation for importing all classes included within a specific package.

Key Takeaways

In this article, we have extensively discussed the Constructors in Java along with types of constructors, rules for creating a constructor as well as constructor overloadingWe hope that this blog has helped you enhance your knowledge of Constructors in Java, and if you would like to learn more, check out our articles on Library. Do upvote our blog to help other ninjas grow. Happy Coding!

Recommended Readings:

Live masterclass