• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

SoftwareTestingo - Jira Selenium Protractor Testing SDLC Agile Methodology

Java Selenium Tutorial & Testing Interview Questions

  • Home
  • Interview Questions
  • Java
  • Java Programs
  • Test Cases
  • Selenium
  • Manual Testing
  • Difference
  • Search
SoftwareTestingo » Java » Java Tutorial » Constructor in Java with With Example & How to Use in Programming Language

Constructor in Java with With Example & How to Use in Programming Language

Last Updated on: October 20, 2019 By Softwaretestingo Editorial Board

What We Are Learn On This Post

  • What is Constructor in Java?
  • The need for Constructor
  • How to Define a Constructor in Java
  • How does constructor work?
  • Types Of Constructors
  • Default Constructor In Java
  • ImportPoint Of Default Constructor
  • No-args Constructor
  • Parameterised constructor
  • Constructor Chaining
  • Use of Super() In Constructor
  • Constructor Overloading
  • New Thing: How Default Constructor & Static Block Called In Java With Example?
  • How The Default constructor Called in Java With Example
  • Copy Constructor

Java Constructor: Still, now we have discussed the basic topics of core Java tutorial. Now we are going to learn new thing like in the last post we have learned about the continuing statement. In this post, we are going to learn about a Java constructor also how to create and use the constructor with the help of some simple and easy examples.

What is Constructor in Java?

The constructor is also a block of code which is much similar to a method but not an actual method because it is used to initialise the newly created objects. It will be called automatically when an instance of a class is created, and memory is allocated for that object.

The need for Constructor

We know that when we are creating a class, the classes have some class variables & methods. So when we are creating an object of that class that time, the variables have some values. So constructor is used to assigning values to the class variables at the time of object creation. It may be done by the programmer or by Java itself (Default Constructor).

How to Define a Constructor in Java

There are some predefined rules which we need to follow at the time of creating constructor, that are:

  • The constructor name should be same as the class name.
  • The constructor must have no explicit return type
  • A Java Constructor cannot be an abstract, static, final and synchronised.

Let’s take a simple Java program example and try to understand how a Java constructor is declared. In the below, you can see there a simple MyClass  java class with a single constructor

public class MyClass 
{
   public MyClass() 
   {

   }
}

In the above example:

public MyClass() 
{

}

In the above case, MyClass() Is a constructor, from that, the first Public part is an access modifier. It is the same meaning as for the methods and variables. By this, we determine what classes can access the constructor.

The second part is the name of the constructor, which is MyClass and that also the class name. Using the class name for the constructor gives a signal to the java compiler that it is a constructor. If you have noticed, then you can find that there is no return type like methods.

The third part of Java constructor is the list of parameter a constructor can take. We can define the parameter inside the (). in the above declaration; you can see that we have not mentioned any parameters. Still, later, we will see the examples of how to define parameters for a constructor.

The Fourth part is the body part of a constructor which we can define inside the brackets {}. in the above example we have not defined the body for the constructor that’s why such type of constructor is called “empty” constructor.

How does constructor work?

If we take the above example for knowing how a constructor works, let’s create an object of that class like below

MyClass obj = new MyClass();

When we create an object like that, then it internally invokes the constructor to initialise the newly created object. you may be a little bit confused regarding how it initialises let’s take another example to know a better way:

public class Hello
{
   String name;
   //Constructor
   Hello()
   {
      name = "www.softwaretestingo.com";
   }
   public static void main(String[] args) 
   {
      Hello obj = new Hello();
      System.out.println(obj.name);
   }
}

In the above example, we are creating an object by using the new keyword, like below

Hello obj=new Hello();

When the Java compiler executes the above statement, it calls the constructor to initialise the variables or members. After complete the execution of constructor again, the flow comes back to the main method for executing the rest of the statements.

Types Of Constructors

In Java, we have mainly three types of constructor:

  • Default Constructor
  • No-arg Constructor
  • Parameterized Constructor

Default Constructor In Java

It is not compulsory to provide a constructor in a class. If we are not providing or mentioned any constructor in a class, then the java provides a default constructor to us for the use. Let’s take a simple Java program to understand where a default constructor is used since we are not mentioned any constructor.

public class Data 
{
   public static void main(String[] args) 
   {
      Data d = new Data();
   }
}

ImportPoint Of Default Constructor

  • The main role of default constructor is to initialise the object and return the execution flow to the calling code.
  • When there is no constructor defined in the class, then a default constructor is provided by the java compiler and its always without any argument.

No-args Constructor

When a constructor without any argument or parameter called No-arg constructor. It’s very much similar to the default constructor. Let’s have a look at No-arg constructor in Java.

class Demo
{
   public Demo()
   {
      System.out.println("This is a no argument constructor");
   }
   public static void main(String args[]) 
   {
      Demo obj = new Demo();
   }
}

When Demo obj = new Demo(); statement execute, It called the Demo constructor and print the message in the console.

Parameterised constructor

A Constructor with argument/parameter is called as a parametrised constructor. If we want to initialise the members or fields of a class with our own, that time we have to use a parameterised constructor.

public class Employee 
{
   int empId;
   String empName;
   //parameterized constructor with two parameters
   Employee(int id, String name){
      this.empId = id;
      this.empName = name;
   }
   void info()
   {
      System.out.println("Id: "+empId+" Name: "+empName);
   }
   public static void main(String args[])
   {
      Employee obj1 = new Employee(10245,"Chaitanya");
      Employee obj2 = new Employee(92232,"Negan");
      obj1.info();
      obj2.info();
   }
}

What if you implement only parameterised constructor in a class?

Let us take an example to understand what’s the problems we are going to face when we have declared only parameterised constructors

class Example3
{
   private int var;
   public Example3(int num)
   {
      var=num;
   }
   public int getValue()
   {
      return var;
   }
   public static void main(String args[])
   {
      Example3 myobj = new Example3();
      System.out.println("value of var is: "+myobj.getValue());
   }
}

Output: If we run the above program, then we will get a compilation error. When the Java compiler execute this statement

Example3 myobj = new Example3();

The above statement will invoke the default constructor, but in our program, there is no default constructor. Because when we don’t implement any constructor in our program that time java compiler implements the default constructor in our class but when we implement any constructor that time you don’t receive the default constructor which was provided by the compiler.

If we remove the parametrised constructor, then the program runs appropriately because that time Java compiler inserts the default constructor into the code.

Constructor Chaining

When a constructor of class calls another constructor of the same class that’s called constructor Chaining. For better understanding, let us go with a simple program.

Use of Super() In Constructor

Whenever a child class constructor wants to implicitly call the constructor of the parent class at that time we can use the super(), in all the sub-classes the first statement of a child class constructor is a super(); statement.

class MyParentClass 
{
   MyParentClass()
   {
      System.out.println("MyParentClass Constructor");
   }
}
class MyChildClass extends MyParentClass
{
   MyChildClass() 
   {
      System.out.println("MyChildClass Constructor");
   }
   public static void main(String args[]) 
   {
      new MyChildClass();
   }
}

Constructor Overloading

Constructor overloading in Java is a concept of having more then one constructor with different parameters list and each constructor is performing a different task as per the requirement.

New Thing: How Default Constructor & Static Block Called In Java With Example?

Default Constructor Java Program: How Default Constructor & Static Block Called In Java With Example?

package com.java.Softwaretestingblog;
public class DefaultconstructorCallingVSStatic
{
  DefaultconstructorCallingVSStatic ()
  {
    System.out.println ("Default Constructor Called");
  }
  static
  {
    System.out.println ("Static Block Executed");
  } public static void main (String[]args)
  {
    DefaultconstructorCallingVSStatic obj =
      new DefaultconstructorCallingVSStatic ();
  }

}
Check Also: Declare and Implement Interface in java

Output:

Static Block Executed
Default Constructor Called

How The Default constructor Called in Java With Example

package com.java.Softwaretestingblog;
public class Default_constructor {
   Default_constructor()
   {
      System.out.println("Default Constructor Called");
   }
   public static void main(String[] args) {
      // TODO Auto-generated method stub
      Default_constructor obj=new Default_constructor();
   }
}

Check Also: Static Block Works In Java With Example

Output:

Default Constructor Called

Copy Constructor

In Java, the copy constructor is mainly used to copy the values of one object to another object.

A class inherits constructor Java Program: How To Check Class inherits constructor of other class or Not?

package com.java.Softwaretestingblog;
class a
{
   a()
   {
      System.out.println("Super Class Constructor Called");
   }
}
public class Class_inherits_Class_constructor extends a
{
   Class_inherits_Class_constructor()
   {
      
   }
   public static void main(String[] args) {
      // TODO Auto-generated method stub
      Class_inherits_Class_constructor obj=new Class_inherits_Class_constructor();
   }
}
Check Also: Default constructor Called in Java

Output:

Super Class Constructor Called

Ref: article

    Filed Under: Java Tutorial

    Reader Interactions

    Comments

    1. V. Ramyasai says

      November 11, 2020 at 6:12 PM

      This is the Best Site for the Software Test Engineers

      Reply

    Leave a Reply Cancel reply

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

    Primary Sidebar

    Join SoftwareTestingo Telegram Group

    Tutorials Important Links

    • Software Testing Jobs
    • Manual Testing Tutorial
    • Selenium Tutorial
    • Core Java Tutorial
    • TestNG Tutorial
    • Java Programs
    • Selenium Programs
    • Manual Test Cases
    • Interview Tips
    • Contact US
    • www.softwaretestingo.com

    Important Links

    • Software Testing Interview Questions
    • Agile Interview Questions
    • Manual Testing Interview Questions
    • Testing Interview Questions
    • Selenium Interview Questions
    • Selenium Real Time Interview Questions
    • Selenium WebDriver Interview Questions
    • Automation Framework Interview Questions
    • Appium Interview Questions
    • TestNG Interview Questions
    • Java Interview Questions
    • Core Java Interview Questions

    Categories

    Copyright © 2021 SoftwareTestingo.com ~ Contact Us ~ Sitemap ~ Privacy Policy