Constructors in Java – A Complete Study

constructor in java

Java is a programming language that is absolutely class-based, object-oriented, and designed for having as little implementation dependencies as possible. However, we are not going to discuss all constructor in java in this article.

We will learn about constructors in Java in this blog. And we will learn how to create and use constructors with the help of examples. Usually, a constructor is a block of codes that initializes the newly created object. Let’s dive into deep.

What is Constructor in Java

We use a constructor to initialize the object’s states. A constructor contains a collection of statements or instructions that execute at the time of Object creation as methods. Constructors are a block of codes that is similar to the method. But there are two exceptions – its name is the same as the class name used, and there is no return type. We can call a constructor when an instance of the class is created.

We invoke an instructor and return the object of the class when we use the new keyword to make an instance of a class. As the constructor only returns the object to the class, java runtime does the work, and we are not supposed to add a return type to it.

The constructor will be a method of the class if you add a return type to it. And that is the way a java runtime differentiates between a normal method and a constructor. Let’s take MyClass as a class.

public MyClass () {

        System.out.println(“MyClass Constructor”);

} 

public MyClass MyClass () {

        System.out.println(“MyClass Method”);

        return new MyClass ();

}

If you notice you can see that there is no return type and no return statement and here, the first one is a constructor. The second one is a normal method, here you are calling the first constructor again to get MyClass instance and return it. I will recommend you not to use the same method name as the class name because it will create confusion.

How Does A Constructor Work?

An example should make you clear on how a constructor work. Let’s have a class MyClass. And then you will create the object of MyClass such as:

MyClass obj = new MyClass()

The keyword new here to create the object of your class MyClass and invokes the constructor to begin this newly created object. That is how a constructor in Java works.

Purpose of A Constructor in Java

We use a constructor to initialize the instances of our classes. A constructor can make a new object, often with parameters specifying the initial state or other relevant information about the object. The primary purpose of a constructor is a method that you can use to ensure that the objectives of your class are valid.

If you want, your class will have a single integer field that will always be larger than zero. Here is the code to do that:

public class A {

     private int number;

    public A(int number) {

        setNumber(number);

     }

 public void setNumber(int number) {

        if (number < 1) {

            throws IllegalArgumentException(“A cannot store anything smaller than 1”);

        }

        this.number = number;

     }

In the above code, you may think you are doing something redundant, but actually, you are ensuring that the number is always valid.

Characteristics of Constructor in Java

Here you will find some top features of Java constructors. Let’s have a look.

  • Constructors cannot become private.
  • A constructor cannot become an abstract, static, final, native, or synchronized.
  • A constructor can be overloaded.
  • Constructors will never return a value.
  • An interface will not have the constructor.
  • Constructors cannot have any return value, not even avoid.
  • An abstract class may have a constructor.
  • The constructor’s name should be similar to the class name inside which it resides.
  • Constructors will be called automatically when an object is created.
See also  Baixar WhatsApp GB Download

We know instance variables and methods of a class as members of a class. Constructors are not members. And that is why constructors cannot be inherited. Calling a constructor as final is meaningless and has no value as constructor cannot be overridden.

Types of Constructor in Java

I have found three types of constructors in Java. By the way, some say it two or more.

  • Default Constructor.
  • No-Args Constructor.
  • Parameterized Constructor.

Let’s have a detailed look at the types of Constructors.

Default Constructor in Java.

Java compiler always inserts a default constructor into your code on your behalf if you do not supply a constructor for an instantiable class. That is why this constructor is called a default constructor. You may search it on your source code, but you will not find it as it might be inserted into the system when compilation and exists in .class file.

A default constructor is always language-dependent. It may feel confusing that initialize data members to zero or other same values, or it may do nothing.

package com.journaldev.constructor;

 public class Data {

 

          public static void main(String[] args) {

                   Data d = new Data();

          }

}

 Here default constructor role is to initialize the object, and one more thing is to return it to calling code. Default constructors are always free from the argument, and Java provides compiler when there is no existing constructor defined. We are okay with the default constructor because other properties can be accessed and initialized via getter setter methods.

No-Args Constructor in Java

No-args constructor does not argue, and that is the reason for calling it no-args constructor. You can say it is overriding the default constructor and do some pre-initialization stuff like checking resources, network connection, and logging. Let’s see the code of no-args constructor.

package com.journaldev.constructor;

 public class Data {

        //no-args constructor

          public Data() {

                   System.out.println(“No-Args Constructor”);

          }

          public static void main(String[] args) {

                   Data d = new Data();

          }

}

By calling new Data(), you are requesting the no-args constructor.

Parameterized Constructor in Java

A parameterized constructor can take a minimum of one argument. The first values have to pass as arguments in the constructor function whenever an object is called in a parameterized constructor. But, it will now work usually as a normal way of object declaration doesn’t work. You can call the constructors explicitly or implicitly. The rules for calling implicitly is called shorthand rules.

Rules for Creating Constructor in Java

You can use access modifiers when you declare a constructor. Access modifiers control the object creation. In other words, you may have private, protected, public, or default constructor in Java.

However, there are three rules for defining a constructor:

  1. Your constructor name should be the same as its class name.
  2. The contractor should have no explicit return type.
  3. Java constructor should not be abstract, static, final, and synchronized.

Defining A Constructor in Java

I will give you some simple Java constructor declaration example. You will be able to know how to set a Java constructor.

Public Class MyClass {

             Public MyClass() {

     }

}

Here the constructor is:

public MyClass() {

}

You will notice that the first part of a java constructor declaration is an access modifier. It has the same meaning as methods and fields have. The determine what classes can access or call the constructor.

The second part declaration is the name of the class of constructor. You may notice that, as other methods have, there is no return type in the constructor.

The third part java declaration is a full list of parameters of construction that can take. There are no parameters declared.

The last and fourth part of Java’s declaration is the body itself of the constructor. It is defined inside the brackets and after the parameter list. As the constructor has no operation inside the constructor body, it is called an “empty” constructor.

See also  POCO F1 Fastboot ROM: How to Install and Download

Constructor Overloading

We know that constructors can be overload like methods. We will have some basic ideas of what constructor overloading is and why we do it.

It is a concept of having more than one constructor with different kinds of parameter listings. So that every constructor can perform a different task. For example, a vector class has four types of constructors. When we do not specify the initial capacity and capability increment, then you can simply use the default constructor of vector class, such as Vector v = new Vector (). By the way, whenever you require to specify the capacity and increment then you should call the parameterized constructor of Vector class with just two int arguments like this: Vector v = new Vector (10, 5);

Example of constructor overloading:

We are making a code snippet of two objects of class StudentsData. One is with a default constructor, and the second one is using a parameterized constructor. Both of the constructors have different initializations code here. Similarly, you can make any number of constructions with different-2 initializations code for the different-2 purpose.

class StudentsData

{

   private int stuID;

   private String stuName;

   private int stuAge;

   StudentsData ()

   {

       //Default constructor

       stuID = 100;

       stuName = “New Student”;

       stuAge = 18;

   }

   StudentsData (int num1, String str, int num2)

   {

       //Parameterized constructor

       stuID = num1;

       stuName = str;

       stuAge = num2;

   }

   //Getter and setter methods

   public int getStuID() {

       return stuID;

   }

   public void setStuID(int stuID) {

       this.stuID = stuID;

   }

   public String getStuName() {

       return stuName;

   }

   public void setStuName(String stuName) {

       this.stuName = stuName;

   }

   public int getStuAge() {

       return stuAge;

   }

   public void setStuAge(int stuAge) {

       this.stuAge = stuAge;

   }

 

   public static void main(String args[])

   {

       //This object creation would call the default constructor

       StudentsData myobj = new StudentsData ();

       System.out.println(“Student Name is: “+myobj.getStuName());

       System.out.println(“Student Age is: “+myobj.getStuAge());

       System.out.println(“Student ID is: “+myobj.getStuID());

 

       /*This object creation would call the parameterized

        * constructor StudentsData (int, String, int)*/

       StudentsData myobj2 = new StudentsData (555, “Chaitanya”, 25);

       System.out.println(“Student Name is: “+myobj2.getStuName());

       System.out.println(“Student Age is: “+myobj2.getStuAge());

       System.out.println(“Student ID is: “+myobj2.getStuID());

  }

}

Difference Between Method and Constructor in Java

  1. A precise method is used to express the behavior of an object—to initialize the state of an object, and we use a constructor.
  2. The method should have a return type—While a contractor should not have.
  3. We invoked the method explicitly – on the other hand, a constructor is invoked implicitly.
  4. The compiler doesn’t supply the method – When you do not use any constructor in a class the java compiler provides one.
  5. The name of the method might be the same or different – A constructor name must be the same as the class name
  6. The purpose of the method is to do a task by executing java code – and the meaning of a constructor is to begin the object of a class.
  7. Methods can be abstract, final, and synchronized – on the other hand, and a constructor cannot be like this.
  8. Methods have return type – but constructors do not have any.

Some Quick Notes of Constructor in Java

Whenever you instantiate an object, a constructor is invoked implicitly. It is one of the most prominent characteristics of a constructor.

There are two rules available for creating a constructor for developers. One is a constructor that will have been matched with the class name and including case. And the second one is a java constructor should not have a return type—this crucial part of java constructor.

There is a type of constructor like if classed do not have any constructor, java compiler will create one default constructor in the time of a run. And other kinds of constructors are No-Arg Constructor, and it is a constructor who does not accept any arguments at all. And the third one is the parameterized constructor. A parameterized constructor utilizes specifically for specifying the values of variables in an object.

There is not abstract or static or final in constructors.

A constructor cannot be overridden, but it can be overloaded.

Each class has a contractor, and it can be a normal class or abstract. Constructors do not have any return type, and they are not methods.

A java constructor may also invoke another constructor by using brackets like (). But it should be in the same class.

The interface doesn’t have constructors.

Overloading is possible in java constructors, but remember that overridden is forbidden.

 

 

 

Leave a Reply

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