Java Tutorial

Java methods, java classes, java file handling, java how to, java reference, java examples, java constructors.

A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes:

Create a constructor:

Try it Yourself »

Note that the constructor name must match the class name , and it cannot have a return type (like void ).

Also note that the constructor is called when the object is created.

All classes have constructors by default: if you do not create a class constructor yourself, Java creates one for you. However, then you are not able to set initial values for object attributes.

Advertisement

Constructor Parameters

Constructors can also take parameters, which is used to initialize attributes.

The following example adds an int y parameter to the constructor. Inside the constructor we set x to y (x=y). When we call the constructor, we pass a parameter to the constructor (5), which will set the value of x to 5:

You can have as many parameters as you want:

Get Certified

COLOR PICKER

colorpicker

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

[email protected]

Top Tutorials

Top references, top examples, get certified.

Learn Java practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn java interactively, java introduction.

  • Java Hello World
  • Java JVM, JRE and JDK
  • Java Variables and Literals
  • Java Data Types
  • Java Operators
  • Java Input and Output
  • Java Expressions & Blocks
  • Java Comment

Java Flow Control

  • Java if...else
  • Java switch Statement
  • Java for Loop
  • Java for-each Loop
  • Java while Loop
  • Java break Statement
  • Java continue Statement
  • Java Arrays
  • Multidimensional Array
  • Java Copy Array

Java OOP (I)

  • Java Class and Objects
  • Java Methods
  • Java Method Overloading
  • Java Constructor
  • Java Strings
  • Java Access Modifiers
  • Java this keyword
  • Java final keyword
  • Java Recursion
  • Java instanceof Operator

Java OOP (II)

  • Java Inheritance
  • Java Method Overriding
  • Java super Keyword
  • Abstract Class & Method
  • Java Interfaces
  • Java Polymorphism
  • Java Encapsulation

Java OOP (III)

  • Nested & Inner Class
  • Java Static Class
  • Java Anonymous Class
  • Java Singleton
  • Java enum Class

Java enum Constructor

  • Java enum String

Java Reflection

  • Java Exception Handling
  • Java Exceptions
  • Java try...catch
  • Java throw and throws
  • Java catch Multiple Exceptions
  • Java try-with-resources
  • Java Annotations
  • Java Annotation Types
  • Java Logging
  • Java Assertions
  • Java Collections Framework
  • Java Collection Interface
  • Java List Interface
  • Java ArrayList
  • Java Vector
  • Java Queue Interface
  • Java PriorityQueue
  • Java Deque Interface
  • Java LinkedList
  • Java ArrayDeque
  • Java BlockingQueue Interface
  • Java ArrayBlockingQueue
  • Java LinkedBlockingQueue
  • Java Map Interface
  • Java HashMap
  • Java LinkedHashMap
  • Java WeakHashMap
  • Java EnumMap
  • Java SortedMap Interface
  • Java NavigableMap Interface
  • Java TreeMap
  • Java ConcurrentMap Interface
  • Java ConcurrentHashMap
  • Java Set Interface
  • Java HashSet
  • Java EnumSet
  • Java LinkedhashSet
  • Java SortedSet Interface
  • Java NavigableSet Interface
  • Java TreeSet
  • Java Algorithms
  • Java Iterator
  • Java ListIterator
  • Java I/O Streams
  • Java InputStream
  • Java OutputStream
  • Java FileInputStream
  • Java FileOutputStream
  • Java ByteArrayInputStream
  • Java ByteArrayOutputStream
  • Java ObjectInputStream
  • Java ObjectOutputStream
  • Java BufferedInputStream
  • Java BufferedOutputStream
  • Java PrintStream

Java Reader/Writer

  • Java Reader
  • Java Writer
  • Java InputStreamReader
  • Java OutputStreamWriter
  • Java FileReader
  • Java FileWriter
  • Java BufferedReader
  • Java BufferedWriter
  • Java StringReader
  • Java StringWriter
  • Java PrintWriter

Additional Topics

  • Java Scanner Class
  • Java Type Casting
  • Java autoboxing and unboxing
  • Java Lambda Expression
  • Java Generics
  • Java File Class
  • Java Wrapper Class
  • Java Command Line Arguments

Java Tutorials

Java this Keyword

  • Java Singleton Class
  • Java Abstract Class and Abstract Methods

Java Constructors

A constructor in Java is similar to a method that is invoked when an object of the class is created.

Unlike Java methods , a constructor has the same name as that of the class and does not have any return type. For example,

Here, Test() is a constructor. It has the same name as that of the class and doesn't have a return type.

Also Read: Why do constructors not return values

  • Example: Java Constructor

In the above example, we have created a constructor named Main() .

Inside the constructor, we are initializing the value of the name variable .

Notice the statement creating an object of the Main class.

Here, when the object is created, the Main() constructor is called. And the value of the name variable is initialized.

Hence, the program prints the value of the name variables as Programiz .

Types of Constructor

In Java, constructors can be divided into three types:

  • No-Arg Constructor
  • Parameterized Constructor
  • Default Constructor

1. Java No-Arg Constructors

Similar to methods, a Java constructor may or may not have any parameters (arguments).

If a constructor does not accept any parameters, it is known as a no-argument constructor. For example,

Example: Java Private No-arg Constructor

In the above example, we have created a constructor Main() .

Here, the constructor does not accept any parameters. Hence, it is known as a no-arg constructor.

Notice that we have declared the constructor as private.

Once a constructor is declared private , it cannot be accessed from outside the class.

So, creating objects from outside the class is prohibited using the private constructor.

Here, we are creating the object inside the same class.

Hence, the program is able to access the constructor. To learn more, visit Java Implement Private Constructor .

However, if we want to create objects outside the class, then we need to declare the constructor as public .

Example: Java Public no-arg Constructors

Also Read: Java Access Modifier

2. Java Parameterized Constructor

A Java constructor can also accept one or more parameters. Such constructors are known as parameterized constructors (constructors with parameters).

Example: Parameterized Constructor

Here, the constructor takes a single parameter. Notice the expression:

Here, we are passing the single value to the constructor.

Based on the argument passed, the language variable is initialized inside the constructor.

3. Java Default Constructor

If we do not create any constructor, the Java compiler automatically creates a no-arg constructor during the execution of the program.

This constructor is called the default constructor.

Example: Default Constructor

Here, we haven't created any constructors.

Hence, the Java compiler automatically creates the default constructor.

The default constructor initializes any uninitialized instance variables with default values.

To learn more, visit Java Data Types .

In the above program, the variables a and b are initialized with default value 0 and false respectively.

The above program is equivalent to:

  • Important Notes on Java Constructors
  • Constructors are invoked implicitly when you instantiate objects.
  • The two rules for creating a constructor are: 1. The name of the constructor should be the same as the class. 2. A Java constructor must not have a return type.
  • If a class doesn't have a constructor, the Java compiler automatically creates a default constructor during run-time. The default constructor initializes instance variables with default values. For example, the int variable will be initialized to 0
  • Constructor types: No-Arg Constructor - a constructor that does not accept any arguments Parameterized constructor - a constructor that accepts arguments Default Constructor - a constructor that is automatically created by the Java compiler if it is not explicitly defined.
  • A constructor cannot be abstract or static or final .
  • A constructor can be overloaded but can not be overridden.
  • Constructors Overloading in Java

Similar to Java method overloading , we can also create two or more constructors with different parameters. This is called constructor overloading.

Example: Java Constructor Overloading

In the above example, we have two constructors: Main() and Main(String language) .

Here, both the constructors initialize the value of the variable language with different values.

Based on the parameter passed during object creation, different constructors are called, and different values are assigned.

It is also possible to call one constructor from another constructor. To learn more, visit Java Call One Constructor from Another .

Note : We have used this keyword to specify the variable of the class. To know more about this keyword, visit Java this keyword .

  • Enum Constructor
  • Constructor Call
  • Private Construction Implementation

Table of Contents

  • Introduction
  • Java No-Arg Constructors
  • Java Parameterized Constructor
  • Java Default Constructor

Sorry about that.

Related Tutorials

Java Tutorial

Javatpoint Logo

Java Object Class

Java inheritance, java polymorphism, java abstraction, java encapsulation, java oops misc.

JavaTpoint

Rule: If there is no constructor in a class, compiler automatically creates a default constructor.

Java default constructor

Q) What is the purpose of a default constructor?

The default constructor is used to provide the default values to the object like 0, null, etc., depending on the type.

Example of default constructor that displays the default values

Explanation: In the above class,you are not creating any constructor so compiler provides you a default constructor. Here 0 and null values are provided by default constructor.

Java Parameterized Constructor

A constructor which has a specific number of parameters is called a parameterized constructor.

Why use the parameterized constructor?

The parameterized constructor is used to provide different values to distinct objects. However, you can provide the same values also.

Example of parameterized constructor

In this example, we have created the constructor of Student class that have two parameters. We can have any number of parameters in the constructor.

Constructor Overloading in Java

In Java, a constructor is just like a method but without return type. It can also be overloaded like Java methods.

Constructor overloading in Java is a technique of having more than one constructor with different parameter lists. They are arranged in a way that each constructor performs a different task. They are differentiated by the compiler by the number of parameters in the list and their types.

Example of Constructor Overloading

Difference between constructor and method in java.

There are many differences between constructors and methods. They are given below.

Java Constructors vs. Methods

Java Copy Constructor

There is no copy constructor in Java. However, we can copy the values from one object to another like copy constructor in C++.

There are many ways to copy the values of one object into another in Java. They are:

  • By constructor
  • By assigning the values of one object into another
  • By clone() method of Object class

In this example, we are going to copy the values of one object into another using Java constructor.

Copying values without constructor

We can copy the values of one object into another by assigning the objects values to another object. In this case, there is no need to create the constructor.

Q) Does constructor return any value?

Yes, it is the current class instance (You cannot use return type yet it returns a value).

Can constructor perform other tasks instead of initialization?

Yes, like object creation, starting a thread, calling a method, etc. You can perform any operation in the constructor as you perform in the method.

Is there Constructor class in Java?

What is the purpose of constructor class.

Java provides a Constructor class which can be used to get the internal information of a constructor in the class. It is found in the java.lang.reflect package.

Youtube

  • Send your Feedback to [email protected]

Help Others, Please Share

facebook

Learn Latest Tutorials

Splunk tutorial

Transact-SQL

Tumblr tutorial

Reinforcement Learning

R Programming tutorial

R Programming

RxJS tutorial

React Native

Python Design Patterns

Python Design Patterns

Python Pillow tutorial

Python Pillow

Python Turtle tutorial

Python Turtle

Keras tutorial

Preparation

Aptitude

Verbal Ability

Interview Questions

Interview Questions

Company Interview Questions

Company Questions

Trending Technologies

Artificial Intelligence

Artificial Intelligence

AWS Tutorial

Cloud Computing

Hadoop tutorial

Data Science

Angular 7 Tutorial

Machine Learning

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures

DAA tutorial

Operating System

Computer Network tutorial

Computer Network

Compiler Design tutorial

Compiler Design

Computer Organization and Architecture

Computer Organization

Discrete Mathematics Tutorial

Discrete Mathematics

Ethical Hacking

Ethical Hacking

Computer Graphics Tutorial

Computer Graphics

Software Engineering

Software Engineering

html tutorial

Web Technology

Cyber Security tutorial

Cyber Security

Automata Tutorial

C Programming

C++ tutorial

Control System

Data Mining Tutorial

Data Mining

Data Warehouse Tutorial

Data Warehouse

RSS Feed

The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available. See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases. See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.

Providing Constructors for Your Classes

A class contains constructors that are invoked to create objects from the class blueprint. Constructor declarations look like method declarations—except that they use the name of the class and have no return type. For example, Bicycle has one constructor:

To create a new Bicycle object called myBike , a constructor is called by the new operator:

new Bicycle(30, 0, 8) creates space in memory for the object and initializes its fields.

Although Bicycle only has one constructor, it could have others, including a no-argument constructor:

Bicycle yourBike = new Bicycle(); invokes the no-argument constructor to create a new Bicycle object called yourBike .

Both constructors could have been declared in Bicycle because they have different argument lists. As with methods, the Java platform differentiates constructors on the basis of the number of arguments in the list and their types. You cannot write two constructors that have the same number and type of arguments for the same class, because the platform would not be able to tell them apart. Doing so causes a compile-time error.

You don't have to provide any constructors for your class, but you must be careful when doing this. The compiler automatically provides a no-argument, default constructor for any class without constructors. This default constructor will call the no-argument constructor of the superclass. In this situation, the compiler will complain if the superclass doesn't have a no-argument constructor so you must verify that it does. If your class has no explicit superclass, then it has an implicit superclass of Object , which does have a no-argument constructor.

You can use a superclass constructor yourself. The MountainBike class at the beginning of this lesson did just that. This will be discussed later, in the lesson on interfaces and inheritance.

You can use access modifiers in a constructor's declaration to control which other classes can call the constructor.

About Oracle | Contact Us | Legal Notices | Terms of Use | Your Privacy Rights

Copyright © 1995, 2022 Oracle and/or its affiliates. All rights reserved.

  • Watch & Listen
  • Oracle University

Previous in the Series: Providing Constructors for your Classes

Next in the Series: Creating and Using Objects

Calling Methods and Constructors

Passing information to a method or a constructor.

The declaration for a method or a constructor declares the number and the type of the arguments for that method or constructor. For example, the following is a method that computes the monthly payments for a home loan, based on the amount of the loan, the interest rate, the length of the loan (the number of periods), and the future value of the loan:

This method has four parameters: the loan amount, the interest rate, the future value and the number of periods. The first three are double-precision floating point numbers, and the fourth is an integer. The parameters are used in the method body and at runtime will take on the values of the arguments that are passed in.

Note: Parameters refers to the list of variables in a method declaration. Arguments are the actual values that are passed in when the method is invoked. When you invoke a method, the arguments used must match the declaration's parameters in type and order.

Parameter Types

You can use any data type for a parameter of a method or a constructor. This includes primitive data types, such as doubles, floats, and integers, as you saw in the computePayment() method, and reference data types, such as objects and arrays.

Here is an example of a method that accepts an array as an argument. In this example, the method creates a new Polygon object and initializes it from an array of Point objects (assume that Point is a class that represents an x , y coordinate):

Arbitrary Number of Arguments

You can use a construct called varargs to pass an arbitrary number of values to a method. You use varargs when you do not know how many of a particular type of argument will be passed to the method. It is a shortcut to creating an array manually (the previous method could have used varargs rather than an array).

To use varargs, you follow the type of the last parameter by an ellipsis (three dots, ...), then a space, and the parameter name. The method can then be called with any number of that parameter, including none.

You can see that, inside the method, corners is treated like an array. The method can be called either with an array or with a sequence of arguments. The code in the method body will treat the parameter as an array in either case.

You will most commonly see varargs with the printing methods; for example, this printf() method:

allows you to print an arbitrary number of objects. It can be called like this:

or like this

or with yet a different number of arguments.

Parameter Names

When you declare a parameter to a method or a constructor, you provide a name for that parameter. This name is used within the method body to refer to the passed-in argument.

The name of a parameter must be unique in its scope. It cannot be the same as the name of another parameter for the same method or constructor, and it cannot be the name of a local variable within the method or constructor.

A parameter can have the same name as one of the class's fields. If this is the case, the parameter is said to shadow the field. Shadowing fields can make your code difficult to read and is conventionally used only within constructors and methods that set a particular field. For example, consider the following Circle class and its setOrigin() method:

The Circle class has three fields: x , y , and radius . The setOrigin() method has two parameters, each of which has the same name as one of the fields. Each method parameter shadows the field that shares its name. So using the simple names x or y within the body of the method refers to the parameter, not to the field. To access the field, you must use a qualified name. This will be discussed later in this lesson in the section titled "Using the this Keyword."

Passing Primitive Data Type Arguments

Primitive arguments, such as an int or a double , are passed into methods by value. This means that any changes to the values of the parameters exist only within the scope of the method. When the method returns, the parameters are gone and any changes to them are lost. Here is an example:

When you run this program, the output is:

Passing Reference Data Type Arguments

Reference data type parameters, such as objects, are also passed into methods by value. This means that when the method returns, the passed-in reference still references the same object as before. However, the values of the object's fields can be changed in the method, if they have the proper access level.

For example, consider a method in an arbitrary class that moves Circle objects:

Let the method be invoked with these arguments:

Inside the method, circle initially refers to myCircle . The method changes the x and y coordinates of the object that circle references (that is, myCircle ) by 23 and 56, respectively. These changes will persist when the method returns. Then circle is assigned a reference to a new Circle object with x = y = 0 . This reassignment has no permanence, however, because the reference was passed in by value and cannot change. Within the method, the object pointed to by circle has changed, but, when the method returns, myCircle still references the same Circle object as before the method was called.

In this tutorial

Last update: January 5, 2024

  • [email protected]

constructor assignment in java

What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

FavTutor

  • Don’t have an account Yet? Sign Up

Remember me Forgot your password?

  • Already have an Account? Sign In

Lost your password? Please enter your email address. You will receive a link to create a new password.

Back to log-in

By Signing up for Favtutor, you agree to our Terms of Service & Privacy Policy.

Constructors in Java (with examples)

  • Nov 03, 2023
  • 15 Minutes Read
  • By Nihal Mahansaria

Constructors in Java (with examples)

Java constructors play a crucial role in object-oriented programming by initializing objects and setting their initial values. These are special methods that are automatically invoked when an object of a class is created. In this guide, we will explore the purpose, types, and usage of constructors in Java, along with practical examples and explanations. 

What are Constructors?

In Java, constructors are a fundamental part of object-oriented programming. They are special methods that initialize objects when they are created. Constructors have the same name as the class and art used to set up the initial state of objects.

Constructor Example

Here's a basic example of a constructor:

In this example, we've defined a constructor for the MyClass class, which initializes the value field to 42 when an object is created. When we create an object and access its value, we get the expected output of 42.

Types of Constructors

Let’s look into the different types of constructors and their examples.

1. Default Constructor

A default constructor is automatically created by the compiler if no constructor is defined in the class . It initializes the object with default values, typically zero for numeric types or null for reference types. Let’s see an example of the same.

Explanation:

In the above example, the DefaultConstructorExample class has a default constructor that initializes the value field to 0.

2. Parameterized Constructor

Parameterized constructors accept arguments to initialize an object's state. They allow for customization during object creation. Let’s see an example of the same:

In this example, the ParameterizedConstructorExample class has a parameterized constructor that accepts an initial value as an argument, allowing you to customize the object's state during creation.

3. Copy Constructor

A copy constructor is used to create a new object by copying the values of an existing object . It's particularly useful when you want to create a deep copy of an object. Let’s see an example of the same:

In this example, the CopyConstructorExample class has a copy constructor that takes an instance of the same class as its parameter. It copies the value from the original object to create a new object.

What is Constructor Overloading?

Constructor overloading allows a class to have multiple constructors with different parameter lists . This provides flexibility when creating objects.

Let’s understand it better with an example.

In the ConstructorOverloadingExample class, we've overloaded the constructor by providing two different constructors - one without any parameters and one with a single parameter. This allows you to create objects in multiple ways, depending on your requirements.

Syntax and Usage of Constructors

Let's dive deeper into the initialization and use cases of constructors.

1. Creating a Constructor

To create a constructor in Java, you need to follow these rules:

  • The constructor name must match the class name.
  • Constructors don't have a return type, not void.
  • You can have multiple constructors in a class, as long as they have different parameter lists.

Here's an example of creating a constructor:

In this example, the ConstructorSyntaxExample class has a constructor that initializes the value field with the provided initial value.

2. Constructor Name and Class Name

The name of a constructor must match the class name. This is how Java knows which constructor to call when creating an object.

Let’s understand the naming convention better with an example:

3. Initializing Object State

One of the primary purposes of a constructor is to initialize the state of an object. You can set the initial values for the object's fields within the constructor.

Let’s dive into it’s implementation:

4. Calling Constructors

Constructors are called when you create an object using the new keyword. The appropriate constructor is automatically selected based on the arguments you provide.

Let’s understand this with an example:

In the example above, we create an object of the ConstructorCallExample class by calling its constructor with an initial value of 15.

5. Implicit and Explicit Constructor Calls

When you create an object, you can implicitly or explicitly call a constructor. An explicit constructor call involves specifying the constructor you want to use, while an implicit call relies on Java's default behavior.

Here's an example of the same:

In the example above, the first object (obj1) is created with an explicit constructor call that initializes the value field to 20. The second object (obj2) is created implicitly with an implicit constructor call, resulting in the default initialization of 0 for the value field.

When and How Default Constructors are created

Let’s explore more about default constructors and their use cases:

When and How It's Created

A default constructor is automatically created by the Java compiler if no constructor is defined in a class. This happens under the following circumstances:

  • If you don't define any constructors in your class.
  • If you define at least one constructor with arguments and don't explicitly provide a no-argument constructor.

Let's see an example:

In this example, we haven't defined any constructors explicitly. As a result, the Java compiler automatically provides a default constructor for the DefaultConstructorExample class.

Default Constructor's Role in Object Initialization

The default constructor plays a crucial role in object initialization when no other constructor is specified. It initializes the object with default values, typically zero for numeric types or null for reference types.

Let’s see an example:

In this example, the DefaultConstructorRoleExample class doesn't define any constructors explicitly. As a result, a default constructor is created by the compiler, and when we create an object, it initializes the value field with the default value of 0.

The default constructor is especially important when you want to create objects without passing any arguments or providing custom initialization logic.

When and How  Parameterized Constructors are created

Let’s explore more about parameterized constructors and their use cases:

Defining and Using Parameters

Parameterized constructors allow you to initialize an object's state by providing one or more parameters when creating an object. This is particularly useful when you need to customize the object's state during construction.

Let’s understand this better with an example:

In this example, the ParameterizedConstructorExample class has a parameterized constructor that accepts an initial value as a parameter. This allows you to set the object's state during object creation.

Initializing Object State with Parameters

When you create an object using a parameterized constructor, you can pass values that are used to initialize the object fields.

In the example above, the ParameterizedConstructorUsageExample class defines a parameterized constructor that accepts an initial value. When we create an object and pass 30 as the parameter, the value field is initialized with the provided value.

Constructor Chaining

Constructor chaining is a technique of constructor called another constructor within the class. This can be useful to avoid duplicating initialization logic.

In this example, the ConstructorChainingExample class has two constructors. The default constructor calls the parameterized constructor with a default value of 0 using this(0).

When we create an object using the default constructor, it calls the parameterized constructor with an initial value of 0, resulting in an object with a value of 0.

When and How  Copy Constructors are created

Let’s explore more about copy constructors and their use cases:

Creating a Copy Constructor

A copy constructor is a special type of constructor used to create a new object by copying the values from an existing object. It's particularly useful when you want to duplicate the state of an object.

Here’s an example:

In this example, the CopyConstructorExample class has a copy constructor that takes an instance of the same class as its parameter and copies the value field from the other object.

Purpose and Use of Copy Constructors

The purpose of a copy constructor is to create a deep copy of an object, ensuring that the new object is independent of the original. It's commonly used in scenarios where you need to duplicate the stete of an object without sharing references to the same data.

In this example, we have an original object, and we create a copy of it using the copy constructor. The copy constructor ensures that the new copy object has its independent copy of the value, and changes to one object don't affect the other.

Copy constructors are valuable when working with complex data structures and want to ensure data integrity by duplicating objects instead of sharing references.

More About Constructor Overloading

Let’s explore various scenarios in constructor overloading:

1. Multiple Constructors in a Class

In Java, you can have multiple constructors within a single class. This concept is known as constructor overloading. Each constructor must have a unique parameter list, allowing you to create objects with different initialization options.

In this example, the ConstructorOverloadingExample class demonstrates constructor overloading with two constructors—one with no parameters and another with a single int parameter.

2. Overloading Rules and Method Signature

When overloading constructors (or methods), the key is to have a different method signature for each constructor. The method signature includes the method's neme end the types and order of its parameters.

In this example, the ConstructorOverloadingRulesExample class demonstrates constructor overloading with two constructors—one accepting an int and another accepting a String.

3. Selecting the Appropriate Constructor

When you create an object, Java automatically selects the most appropriate constructor based on the arguments you provide. If you provide an int argument, the constructor that accepts an int will be called. If you provide a String argument, the constructor that accepts a String will be called.

In this example,  we create two objects, obj1 and obj2, with different types of arguments. Java selects the appropriate constructor based on the argument type, allowing you to create objects with different initializations.

Constructor Best Practices

Following a certain set of practices could make the usage of constructors much more easier and efficient. Some of them are:

A. Encapsulation and Constructor Access Modifiers

Encapsulation is a fundamental concept in object-oriented programming. Constructors can be used to ensure that objects are created in a valid and consistent state. By controlling the access to object fields through constructors, you can enforce encapsulation.

Here's an example:

In this example, we use a private constructor to enforce encapsulation and a public factory method, create, for creating objects. The factory method ensures that the initial value is non-negative.

B. Constructor vs. Static Factory Methods

In addition to constructors, Java allows the use of static factory methods for object creation. Static factory methods offer more flexibility and descriptive names, making them a valuable alternative to constructors.

Let's see the implementation:

In this example, we use a static factory method, createWithInitialValue, to create objects. This approach provides a clear and descriptive way to initialize objects.

C. Using Constructors for Dependency Injection

Constructors are commonly used for dependency injection, a design pattern that promotes loosely coupled classes. By injecting dependencies through constructors, you can make your code more testable and maintainable.

In this example, the DependencyInjectionExample class receives a Logger dependency through its constructor, enabling the injection of different logging implementations.

Common Pitfalls while using Constructors

While using constructors, one might come accross some common erros and pitfalls. Some of them are:

A. Constructor Ambiguity

Constructor ambiguity occurs when multiple constructors in a class have similar parameter lists, making it unclear which constructor should be called. This can lead to compilation errors.

In this example, both constructors have the same parameter type (int), which can lead to ambiguity issues when creating objects with an int argument.

B. Initializing Order Issues

In some cases, initialization order can be a pitfall. If you have multiple constructors or complex initialization logic, it's essential to ensure that objects are initialized correctly and consistently.

In this example, there are two constructors with different initialization logic. Depending on the constructor used, the order of initialization can differ, leading to unexpected behavior.

C. Constructor Exception Handling

Constructors can throw exceptions during object creation. It's crucial to handle exceptions appropriately to ensure that objects are constructed safely.

In this example, the constructor throws an IllegalArgumentException if the initial value is negative. Failing to handle such exceptions can lead to runtime errors. 

In this article, we have explored the purpose, types, and usage of constructors in Java. Constructors play a vital role in object initialization and allow for flexible and customizable object creation. By using constructors effectively, you can ensure that objects are created in a valid and consistent state, with their attributes properly initialized.

constructor assignment in java

FavTutor - 24x7 Live Coding Help from Expert Tutors!

constructor assignment in java

About The Author

constructor assignment in java

Nihal Mahansaria

More by favtutor blogs, biddecimal class in java (with examples).

constructor assignment in java

Getters and Setters in Java (with Examples)

constructor assignment in java

Enhanced For Loop Java (with Codes)

constructor assignment in java

  • Blogs by Topic

The IntelliJ IDEA Blog

IntelliJ IDEA – the Leading Java and Kotlin IDE, by JetBrains

  • Twitter Twitter
  • Facebook Facebook
  • Youtube Youtube

Constructor Makeover in Java 22

Mala Gupta

Typically, we create alternative solutions for tasks that are necessary, but not officially permitted. For instance, executing statements before super() in a derived class constructor was not officially allowed, even though it was important for, say, validating values being passed to the base class constructor. A popular workaround involved creating static methods to validate values and then calling these methods on the arguments of super() . Though this approach worked well, it could make the code look complicated. This is changing with Statements before super() , a preview language feature in Java 22.

By using this feature, you can opt for a more direct approach, that is, drop the workaround of creating static methods, and execute code that validates arguments, just before calling super() . Terms and conditions still apply, such as, not accessing instance members of a derived class before execution of super() completes.

I know you are wondering, why was this constraint added in the first place, how is this being resolved, does it change the internal JVM working, and the most important question – how can you benefit from this feature? I’ll answer all these questions in this blog post.

Let’s start with an example.

Example 1 – validating values passed to super() in a derived class constructor

Imagine you need to create a class, say, IndustryElement , that extends class Element , which is defined as follows:

The constructor of the class Element misses checking if the atomicNumber is in the range of 1-118 (all known elements have atomic numbers between 1 to 118). Often the source code of a base class is not accessible or open for modification. How would you validate the values passed to atomicNumber in the constructor of class IndustryElement ?

Until Java 21, no statements were allowed to execute before super() . Here’s one of the ways we developers found a workaround by defining and calling static methods (static methods belong to a class and not to instances and can be executed before any instance of a class exists):

Starting Java 22, you could inline the contents of your static method in the constructor for your derived class, as shown in the following gif:

Here’s the resultant code for your reference:

I know you have questions about the preceding code, but before we move forward, let me share the IntelliJ IDEA Project Configuration you’d need for working with this feature in IntelliJ IDEA. If you are already familiar with it, skip the next section. IntelliJ IDEA Configuration

Java 22 support is available in IntelliJ IDEA 2024.1 EAP . The final release of this version is planned for March 2024.

In your Project Settings, set the SDK to Java 22. For the language level, select ‘22 (Preview) – Statements before super(), string templates (2nd preview etc.)’ on both the Project and Modules tab, as shown in the below settings screenshot:

constructor assignment in java

Why do you care about this feature? Often folks ask – isn’t it better to enclose the validation logic in a separate method since it makes the code easier to read and understand? For example, in the previous example, wouldn’t it be better to keep the validation logic in a separate method? My opinion – though it is a good question, it is not what this feature is trying to address.

You could call the static method checkRange, before calling super() in the constructor of class IndustryElement as follows (the validation code is still delegated to another method):

I believe one of the real benefits here is that you have a choice. You are free to define code in the way you see it, that is, validate the arguments, if there are no issues, call the super class constructor.

You might argue that one could call the super class constructor first, and validate its arguments later. I would never recommend it. It could even lead to technical debts. What if the validation code finds issues but logs an error message, instead of terminating the initialisation process? This is poor coding practice. Why was execution of statements before super not allowed in the past? Compare a base class with a seed and the derived class with a plant that is formed using it. A seed needs to be fully formed, before any part of the plan or its processes can be accessed. Similarly, the constructor of a base class must execute completely, before any member variables or methods of a derived class can be called. So with this constraint, the Java platform was trying to protect the state of your instances.

Also, if you do not explicitly call the constructor of a base class in a derived class constructor, the compiler inserts a call to the implicit, no-argument, base class constructor. In short, at least one base class constructor always gets executed for a derived class, whether you do that explicitly or not. This was the case since Java 1.0. How does it work behind the scenes? The language syntax has been relaxed but it doesn’t change or impact the internal JVM instructions. There are no changes to the JVM instructions for this new feature because the order of execution of the constructors still remains unchanged – from base class to a derived class. Also, this feature still doesn’t allow you to use members of a derived class instance, until super() executes.

Let’s access and compare the instruction set of the constructor of class IndustryElement , before and after its modification – one that can execute statements before super() and the one that doesn’t. To do so, use the following command:

Here’s the instruction set for the constructor that doesn’t explicitly execute statements before super() and calls static methods to validate range of atomic number:

constructor assignment in java

Here’s instruction set for the constructor that explicitly executes statements before super() to validate range of atomic number:

constructor assignment in java

The most important point to note here is that in both the cases, the constructor of the base class, that is, Element is called, after the execution of all other statements. Essentially, it means, you are still doing the same thing, it is just packaged in a way that makes things easier for you.

I understand it is difficult to remember what each of these instruction codes means. Access the following link and search for the instruction code and following the above instructions set would be a breeze:

https://docs.oracle.com/javase/specs/jvms/se21/html/jvms-6.html#jvms-6.5.aload_n Can you execute ‘any’ statements before calling super()?

No. If the statements before super() try to access instance variables or execute methods of your derived class, your code won’t compile. For example, if you change the static checkRange() method to an instance method, your code won’t compile, as shown below:

Before everythings gets boring, lets work with another example 🙂 Example 2 – base class constructor parameters that use annotations for validations Assume that constructor of base class Element checks for a non null value being passed to its parameter via @NotNull annotation as follows:

Annotations can give a false sense of security. Even though it might seem that this constructor wouldn’t accept a null value for the parameter color , annotations can be disabled at runtime. So you must include code that checks for null safety in the derived class constructor, as follows:

Example 3 – Transforming variable values received in a derived class constructor, before calling a base class constructor.

Our applications often receive data in multiple and varied formats, and may not be in the format we want to store or use that data. Easy solution-we transform the values to the ones that we require. However, handling the transformation is easier with methods other than the constructors.

Imagine the constructor of the derived class IndustryElement receives the following JSON as a String value:

Or as a Comma Separated value, as follows:

There could be other formats too, say XML. The idea is that the data that is received by the constructor of a derived class can’t be passed to the constructor of a base class in its original form. It must be transformed.

Before this new feature that allowed statements before super() , you would have to define the constructor of the derived class IndustryElement as follows:

With this new feature, you can simplify the preceding code as follows:

Example 4 – Executing statements before this() in constructor of Records Records, as we know can’t extend other records or classes, because they implicitly extend java.lang.Record class. Records can benefit from this feature too by executing statements before calling this() in their constructors.

For example, here’s the code of a record Palette2Colors that represents a color palette with only two colors. For a specific business logic, the constructor uses either a brighter or a darker shade of the color value passed to its constructor:

Imagine when you start using this record, you find multiple use cases where you have to pass an array of colors to this record instead of individual Color instances. You would prefer calling the other constructor since it has additional transformation logic.

Here’s how you might create this additional constructor (before Java 22):

Though the preceding code is valid, this line of code Objects.requireNonNull(colors, "Color arr shouldn't be null")[0] , it is a bit difficult to read. Records can benefit from this feature too, and your could define the preceding constructor as follows (with Java 22):

You might be wondering you could have inlined the code defined in the other constructor in the preceding constructor as follows:

However, this would result in code repetition across constructors, which is never good. What happens if the business logic no longer needs to assign a lighter or darker shade of the color values passed as method arguments, and this logic is changed in just one constructor? Perfect place for bugs to hide! Example 5 – Executing statements before this() in Enum constructors Similar to a record, you could execute statements before this() in Enum constructors too. Here is an example of an enum, say, BrightColor , that defines two constructors:

Example 6 – Executing statements before this() in classes Starting Java 22, you could also execute statements before this() in a class constructor, unless it doesn’t call other instance members of the class. Below is an example:

The benefits of this approach is similar to what we covered in this blog post. The second constructor of class Voter, the one that accepts three method parameters can validate the parameters and then call this() which includes the validation and initialization code. Preview Features Statements before super() is being introduced as a preview language feature in Java 22. With Java’s new release cadence of six months, new language features are released as preview features. They may be reintroduced in later Java versions in the second or more preview, with or without changes. Once they are stable enough, they may be added to Java as a standard language feature.

Preview language features are complete but not permanent, which essentially means that these features are ready to be used by developers, although their finer details could change in future Java releases depending on developer feedback. Unlike an API, language features can’t be deprecated in the future. So, if you have feedback about any of the preview language features, feel free to share it on the JDK mailing list (free registration required).

Because of how these features work, IntelliJ IDEA is committed to only supporting preview features for the current JDK. Preview language features can change across Java versions, until they are dropped or added as a standard language feature. Code that uses a preview language feature from an older release of the Java SE Platform might not compile or run on a newer release.

Summary In Java 22, the feature Statements before super() lets you execute code before calling super() in your derived class constructors, this() in your records or enums, so that you could validate the method parameters, or transform values, as required. This avoids creating workarounds like creating static methods and makes your code easier to read and understand.

This feature doesn’t change how constructors would operate now vs. how they operated earlier – the JVM instructions remain the same.

The relaxation of this syntax rule starting Java 22 still ensures that super() completes before your access any members of a derived class. Your code wouldn’t compile if you try otherwise.

constructor assignment in java

Subscribe to Blog updates

By submitting this form, I agree that JetBrains s.r.o. ("JetBrains") may use my name, email address, and location data to send me newsletters, including commercial communications, and to process my personal data for this purpose. I agree that JetBrains may process said data using third-party services for this purpose in accordance with the JetBrains Privacy Policy . I understand that I can revoke this consent at any time in my profile . In addition, an unsubscribe link is included in each email.

Thanks, we've got you!

Discover more

constructor assignment in java

Easy Hacks: How To Implement Polymorphism in Java

Polymorphism is the ability of an object to take on different forms. In programming, this means that a variable or a method can have different behaviors depending on the type of object it represents. While the term may sound intimidating to beginners, polymorphism is a powerful tool: it helps you re…

Maarten Balliauw

You’re Invited to IntelliJ IDEA Conf 2024!

We are back and excited to invite you to IntelliJ IDEA Conf 2024, a developer-focused, live, online event that is free for all to attend!

Mala Gupta

Java Annotated Monthly – February 2024

Welcome to the February edition of Java Annotated Monthly! We're excited to share this month’s collection of articles brimming with the latest Java news, including a list of the upcoming JEPs for Java 22. What’s more, you’ll also get to explore numerous informative blogs packed with Java tips and tu…

Irina Mariasova

Top 10 UI Updates in IntelliJ IDEA for 2023

Hey there, fellow developers! Today, we want to share the most significant UI updates from 2023 that have transformed how IntelliJ IDEA looks and functions. New UI Of course, the highlight of our recent updates was the launch of our new, clean, and modern UI. This was first announced at the en…

Constructor in Java | Types, Uses, Example

A constructor in Java is a block of code, syntactically similar to a method that is used to initialize the state of an object in a class.

In other words, a constructor is a special member function of a class used to initialize instance variables of a class.

The sole purpose of a constructor is to perform the initialization of data fields of an object in the class.

Java constructor can perform any action but specially designed to perform initializing actions, such as initializing the instance variables with legal initial values.

A constructor within a class allows constructing the object of the class at runtime. It is automatically invoked when an instance of a class is created using the new operator.

Constructors can also accept arguments like methods and can be overloaded. If we try to create an object of the class without specifying any constructor in the class, compiler automatically create a default constructor for us.

Syntax to Declare Constructor in Java

Generally, we declare a constructor inside the public section of the class by the following syntax so that we can create its object in any function. The general syntax to declare a constructor in Java is as:

The following example code defines a constructor in the class.

Here, Rectangle is a class name that must be the same as the name of class that contains constructor. That’s mandatory.

public is an access modifier that indicates that other classes can access the constructor. A constructor can be declared (optionally) as public, protected, and private. These are called access modifiers in Java.

Non-access modifiers cannot be applied with constructors. By mistake, if you apply any other modifiers with constructor except these three access modifiers, you will get a compile-time error.

If you apply a private access modifier with a java constructor, you cannot create an object of that class in other classes. If somebody asks that I want to create a class but nobody should instantiate it, you can say “make the constructor private”.

Characteristics of Java Constructor

There are the following characteristics or features of constructor in Java. They are as follows:

1. Constructor’s name must be exactly the same as the class name in which it is defined. It must end with a pair of simple braces.

2. The constructor should not have any return type even void also because if there is a return type then JVM would consider as a method, not a constructor.

Compiler and JVM differentiate constructor and method definitions on the basis of the return type. Suppose you define the method and constructor with the same name as that of the class name then JVM would differentiate between them by using return type.

It is a common mistake to declare the void keyword before a constructor. For example:

Here, Rectangle() is a method, not a constructor.

3. Java constructor may or may not contain parameters. Parameters are local variables to receive value (data) from outside into a constructor.

4. A constructor is automatically called and executed by JVM at the time of object creation. JVM (Java Virtual Machine) first allocates the memory for variables (objects) and then executes the constructor to initialize instance variables.

5. It is always called and executed only once per object. This means that when an object of a class is created, constructor is called. When we create second object, the constructor is again called during the second time.

a. Numeric variables are set to 0. b. Strings are set to null. c. Boolean variables are set to false.

7. Constructors provide thread safety, meaning no thread can access the object until the execution of constructor is completed.

8. We can do anything in the constructor similar to a method. Using constructors, we can perform all initialization activities of an object.

How to Call Constructor in Java

There are the following ways to call a constructor in java.

1. A a = new A(); // Here, A is name of class. 2. new A(); // It is calling A() constructor. 3. super(); 4. this(); 5. class.forName(“com.scientecheasy.A”).newInstance();

When we create an object of class by using new keyword, a constructor is automatically called by JVM. After creating the object of the class, we cannot call the constructor again.

Consider the following example where we have created an object of a class School.

From the above syntax, you keep the following points in mind. They are:

  • School is the name of the class.
  • sc is an object reference variable which stores the address of the object in the stack memory.
  • School() is a constructor of class.
  • new is a special keyword that allocates the memory to store objects whose type is specified by a constructor. After allocation of memory, it calls constructor to initialize objects, which are stored in the heap ( a region of memory for storing objects).

When the constructor ends, a new keyword returns memory addresses to the object so that it can be accessed from anywhere in the application.

Types of Constructors in Java

Basically, there are three types of constructors in Java programming. They are as:

  • Default Constructor
  • Non-parameterized constructor
  • Parameterized Constructor

Let’s understand the default and parameterized constructors with the help of examples.

Default Constructor in Java with Example

A constructor that has no parameter is known as default constructor in Java . When a class does not declare a constructor, Java compiler automatically adds a constructor for that class.

In other words, the compiler adds a default constructor only when we do not define any constructor explicitly. The constructor added by compiler is called default constructor. Look at the example in the below figure to understand better.

Java default constructor

We cannot pass any argument to default constructor. That’s why it is also known as a no-argument constructor in java. It does not do anything but it allows to create instance of class.

Features of Default Constructor

There are the following features of a default constructor in Java. They are as:

(1) When Java compiler adds a default constructor, it also adds a statement called super() to call the superclass constructor.

(4) It has no throws clause.

(5) The access modifiers of the default constructor should be the same as the access modifier of the class. For example, if the top-level class is declared public, the default constructor should implicitly be declared as public. For example:

Here, the default constructor is public because the top-level class is public.

Example Program based on Default Constructor

Let’s take an example where we will not create any constructor in the class. But Java compiler will automatically put a default constructor in the class. The default constructor will set default values to instance variables.

Suppose we have a class ‘Person’. A person has three major properties like name, age, and address, where the name, age, and address are instance variables declared inside the class.

Program code 1:

Explanation:

In the preceding example program, we have not created any constructor in the class Person. So, java compiler adds a default constructor inside class. null, 0, null is the default values of the instance variables provided by the default constructor.

Non-parameterized Constructor in Java

A constructor which has no parameters in the parentheses but contains statements inside its body is called a non-parametrized constructor . We also call it as a non-argument constructor.

A non-parameterized constructor has the same signature as that of default constructor, except for only one difference between them. Using non-parameterized constructor, we can initialize any values for the instance variables.

Let’s take an example program in which we will initialize different values to instance variables using non-parameterized constructor.

Program code 2:

Memory allocation of constructor in java

We know that p is an object reference variable that contains the address of memory location of objects. Here, 5575 is the address on the stack where we can find other detail of the class like name, age, and address on this address.

A reference variable never contains an object directly. It contains an address that points to data stored in the memory location.

In the above figure, you can see that when we did not initialize values of instance variables in the constructor in program 1, default values for variables have been stored on the heap after calling constructor.

But, when we initialized values of variables in the constructor in program 2, after calling the constructor, default values are eliminated from the memory location and initialized values are stored in the memory location of heap.

Parameterized Constructor in Java with Example

A constructor that takes one or more parameters and contains statements inside its body is called parameterized constructor in Java .

In the parameterized constructor, instance variables automatically initialize at runtime when we pass values to parameters during object creation.

The parameterized constructor is used to provide different values to distinct objects. It allows us to initialize instance variables with unlike values. In the case of the default constructor, values remain the identical for all objects.

An example of parameterized constructor is as follows:

To call the parameterized constructor, we need to pass arguments while creating the object. Therefore, parameterized constructor is also called argument constructor.

The argument can be of any type like integer, array, character, or object. It can take any number of arguments. Java does not provide a parameterized constructor by default.

Note : We cannot define two constructors with the same number of parameters and the same types.

Let’s take an example program where we will define default, one parameter, and two parameter constructors and call them with passing arguments.

Program code 3:

a. When JVM will execute the statement Demo d = new Demo(); it will call default constructor for class.

b. In the next line, JVM will call one argument constructor while executing of new demo(20).

c. The next line new Demo(10,15) will call two arguments constructor. You can see in all the three lines in the main, the same object reference variable has been used. We can also write above three lines of code in this manner:

Let us take an example program in which we will initialize values to the instance variables in two manners. Look at the program source code.

Program code 4:

Constructor with Array of Objects

Let’s take an example program to understand the concept of constructor with array of objects.

Program code 5:

Here, it is important to note that the default constructor is not invoked when the statement Hello[] h = new Hello[4]; is executed. Default constructor is called when h[i] = new Hello(); is executed.

Use of Constructor in Java

The use of constructor in Java is as follows:

  • The constructor is used in java programming to assign the default value of instance variables.
  • Constructor is used to initializing objects of a class and allocate appropriate memory to objects. That is, it is used to initialize the instance variables of a class with a different set of values but it is not necessary to initialize.
  • If you need to execute some code at the time of object creation, you can write them inside the constructor. Generally, it is used for the initialization of instance variables.
  • Use of private constructor

Difference between Constructor and Method in Java

The difference between constructor and method is in the below table:

Key Points of Constructor:

1. The task of a constructor in Java is to initialize instance variables of an object.

2. A constructor of class is automatically executed by JVM when an object is instantiated.

3. When an object of class is instantiated, constructor is called before any methods.

4. If you declare your own constructor, you have to decide what values should be given to instance variables.

5. this and super keyword must be the first line in the constructor.

6. Constructor overloading is possible but overriding is not possible.

7. It cannot be inherited in the subclass.

8. A constructor can also call another constructor of the same class using ‘this’ and for argument constructor use ‘this(para_list).

9. A Constructor is not a keyword in Java.

10. Java constructor is the third possibility to initialize instance variables in a class.

In this tutorial, we have explained types of constructors in Java with the help of various examples. Hope that you will have understood the key features of constructor and practiced all example programs. In the next, we will understand about constructor overloading in Java with examples. Thanks for reading!!

⇐ Prev Next ⇒

Default Constructor in Java – Class Constructor Example

In this article, we will talk about constructors, how to create our own constructors, and what default constructors are in Java.

What is a constructor?

As a class-based object-oriented programming term, a constructor is a unique method used to initialize a newly created object (class). There are a few rules you must follow when creating constructors. These rules include:

  • The name of the constructor must be the same as the class name.
  • The constructor must have no return type.

Before we proceed, let's see what a class looks like in Java:

The code above shows a class called Student with three attributes – firstName , lastName , and age . We will assume that the class is supposed to be a sample for registering students. Recall that the three attributes do not have any values so none of the information is hard coded.

Now we will use constructors to create a new instance of our Student object. That is:

We have created a constructor which we used to initialize the attributes defined in the Student object. The code above is an example of a no-argument constructor. Let's see an example of a different kind now:

Now we have created a parameterized constructor . A parameterized constructor is a constructor created with arguments/parameters. Let's break it down.

We created a new constructor that takes in three arguments – two strings and an integer.

We then linked these arguments to the attributes we defined when we created our class.  Now we have initialized the Student object using a constructor.

Lastly, we created a new instance of the Student object and passed in our arguments. We were able to pass in these arguments because we had already defined them in a constructor.

I created one constructor with three arguments, but you can also create separate constructors for initializing each attribute.

Now that you know what a constructor is in Java and how to use it, let's now look into default constructors.

What is a default constructor?

A default constructor is a constructor created by the compiler if we do not define any constructor(s) for a class. Here is an example:

Can you spot the difference between this and the two previous examples? Notice that we did not define any constructor before creating   myStudent to initialize the attributes created in the class.

This will not throw an error our way. Rather, the compiler will create an empty constructor but you will not see this constructor anywhere in the code – this happens under the hood.

This is what the code above will look like when the compiler starts doing its job:

A lot of people mix up the default constructor for the no-argument constructor, but they are not the same in Java. Any constructor created by the programmer is not considered a default constructor in Java.

In this article, we learned what constructors are and how we can create and use them to initialize our objects.

We also talked about default constructors and what makes them different from no-argument constructors.

Happy Coding!

ihechikara.com

If you read this far, thank the author to show them you care. Say Thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Java Constructor

Java programming tutorial index.

As you all know that all objects that are created must be given initial values which can be done in two ways. The first way of doing this is to use the dot operator to access the instance variable and then to assign values to them individually. It can be a tedious approach to initialize all the variables of the object in this manner.

The second approach takes the help of method like getData() or init() etc., to initialize each object individually using statements like:

Here, in this chapter, you will be dealing with constructors of Java, and learn about how they are used within a Java program and how they are useful Object Oriented Programming concept.

What are Constructors?

Constructors are special member functions whose task is to initialize the objects of its class. It is treated as a special member function because its name is the same as the class name. Java constructors are invoked when their objects are created. It is named such because, it constructs the value, i.e., provide data for the object, i.e., they are used to initialize objects. Every class has a constructor when we don't explicitly declare a constructor for any java class the compiler creates a default constructor for that class which does not have any return type. The constructor in Java cannot be abstract, static, final or synchronized and these modifiers are not allowed for the constructor.

Characteristics of Java Constructors

  • An interface cannot have the constructor.
  • Constructors cannot be private.
  • A constructor cannot be abstract, static, final, native, strictfp, or synchronized
  • A constructor can be overloaded.
  • Constructors cannot return a value.
  • Constructors do not have a return type; not even void.
  • An abstract class can have the constructor.
  • Constructors name must be similar to that of the class name inside which it resides.
  • Constructors are automatically called when an object is created.

Instance variables and methods of a class are known as members of a class. Constructors are not members. For this reason, constructors cannot be inherited; but can be accessed by a subclass. Java constructors do not get inherited; only their members (variables and methods) get inherited. So declaring a constructor as final is useless and has no meaning as constructors cannot be overridden. Again, Java constructors should not be synchronized as it locks the object when created and hence, as long as the object is not created any other object can be instantiated.

Types of Java Constructors

There are two types of constructors:

  • Default constructor (no-arg constructor)
  • Parameterized constructor

Default Constructor

A constructor having no parameter is known as default constructor and no-arg constructor.

The structure of a default constructor is like this:

The syntax of default constructor:

Parameterized Constructor

A constructor having an argument list is known as a parameterized constructor. Parameterized constructors are used to supply dissimilar values to the distinct objects.

The structure of a parameterized constructor in Java is:

Program for Default Constructor

Program for parameterized constructor.

  • 90% Refund @Courses
  • Java Arrays
  • Java Strings
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Spring Boot

Related Articles

  • Solve Coding Problems
  • Java Tutorial

Overview of Java

  • Introduction to Java
  • The Complete History of Java Programming Language
  • C++ vs Java vs Python
  • How to Download and Install Java for 64 bit machine?
  • Setting up the environment in Java
  • How to Download and Install Eclipse on Windows?
  • JDK in Java
  • How JVM Works - JVM Architecture?
  • Differences between JDK, JRE and JVM
  • Just In Time Compiler
  • Difference between JIT and JVM in Java
  • Difference between Byte Code and Machine Code
  • How is Java platform independent?

Basics of Java

  • Java Basic Syntax
  • Java Hello World Program
  • Java Data Types
  • Primitive data type vs. Object data type in Java with Examples
  • Java Identifiers

Operators in Java

  • Java Variables
  • Scope of Variables In Java

Wrapper Classes in Java

Input/output in java.

  • How to Take Input From User in Java?
  • Scanner Class in Java
  • Java.io.BufferedReader Class in Java
  • Difference Between Scanner and BufferedReader Class in Java
  • Ways to read input from console in Java
  • System.out.println in Java
  • Difference between print() and println() in Java
  • Formatted Output in Java using printf()
  • Fast I/O in Java in Competitive Programming

Flow Control in Java

  • Decision Making in Java (if, if-else, switch, break, continue, jump)
  • Java if statement with Examples
  • Java if-else
  • Java if-else-if ladder with Examples
  • Loops in Java
  • For Loop in Java
  • Java while loop with Examples
  • Java do-while loop with Examples
  • For-each loop in Java
  • Continue Statement in Java
  • Break statement in Java
  • Usage of Break keyword in Java
  • return keyword in Java
  • Java Arithmetic Operators with Examples
  • Java Unary Operator with Examples
  • Java Assignment Operators with Examples
  • Java Relational Operators with Examples
  • Java Logical Operators with Examples
  • Java Ternary Operator with Examples
  • Bitwise Operators in Java
  • Strings in Java
  • String class in Java
  • Java.lang.String class in Java | Set 2
  • Why Java Strings are Immutable?
  • StringBuffer class in Java
  • StringBuilder Class in Java with Examples
  • String vs StringBuilder vs StringBuffer in Java
  • StringTokenizer Class in Java
  • StringTokenizer Methods in Java with Examples | Set 2
  • StringJoiner Class in Java
  • Arrays in Java
  • Arrays class in Java
  • Multidimensional Arrays in Java
  • Different Ways To Declare And Initialize 2-D Array in Java
  • Jagged Array in Java
  • Final Arrays in Java
  • Reflection Array Class in Java
  • util.Arrays vs reflect.Array in Java with Examples

OOPS in Java

  • Object Oriented Programming (OOPs) Concept in Java
  • Why Java is not a purely Object-Oriented Language?
  • Classes and Objects in Java
  • Naming Conventions in Java
  • Java Methods

Access Modifiers in Java

  • Java Constructors
  • Four Main Object Oriented Programming Concepts of Java

Inheritance in Java

Abstraction in java, encapsulation in java, polymorphism in java, interfaces in java.

  • 'this' reference in Java
  • Inheritance and Constructors in Java
  • Java and Multiple Inheritance
  • Interfaces and Inheritance in Java
  • Association, Composition and Aggregation in Java
  • Comparison of Inheritance in C++ and Java
  • abstract keyword in java
  • Abstract Class in Java
  • Difference between Abstract Class and Interface in Java
  • Control Abstraction in Java with Examples
  • Difference Between Data Hiding and Abstraction in Java
  • Difference between Abstraction and Encapsulation in Java with Examples
  • Difference between Inheritance and Polymorphism
  • Dynamic Method Dispatch or Runtime Polymorphism in Java
  • Difference between Compile-time and Run-time Polymorphism in Java

Constructors in Java

  • Copy Constructor in Java
  • Constructor Overloading in Java

Constructor Chaining In Java with Examples

  • Private Constructors and Singleton Classes in Java

Methods in Java

  • Static methods vs Instance methods in Java
  • Abstract Method in Java with Examples
  • Overriding in Java
  • Method Overloading in Java
  • Difference Between Method Overloading and Method Overriding in Java
  • Differences between Interface and Class in Java
  • Functional Interfaces in Java
  • Nested Interface in Java
  • Marker interface in Java
  • Comparator Interface in Java with Examples
  • Need of Wrapper Classes in Java
  • Different Ways to Create the Instances of Wrapper Classes in Java
  • Character Class in Java
  • Java.Lang.Byte class in Java
  • Java.Lang.Short class in Java
  • Java.lang.Integer class in Java
  • Java.Lang.Long class in Java
  • Java.Lang.Float class in Java
  • Java.Lang.Double Class in Java
  • Java.lang.Boolean Class in Java
  • Autoboxing and Unboxing in Java
  • Type conversion in Java with Examples

Keywords in Java

  • Java Keywords
  • Important Keywords in Java
  • Super Keyword in Java
  • final Keyword in Java
  • static Keyword in Java
  • enum in Java
  • transient keyword in Java
  • volatile Keyword in Java
  • final, finally and finalize in Java
  • Public vs Protected vs Package vs Private Access Modifier in Java
  • Access and Non Access Modifiers in Java

Memory Allocation in Java

  • Java Memory Management
  • How are Java objects stored in memory?
  • Stack vs Heap Memory Allocation
  • How many types of memory areas are allocated by JVM?
  • Garbage Collection in Java
  • Types of JVM Garbage Collectors in Java with implementation details
  • Memory leaks in Java
  • Java Virtual Machine (JVM) Stack Area

Classes of Java

  • Understanding Classes and Objects in Java
  • Singleton Method Design Pattern in Java
  • Object Class in Java
  • Inner Class in Java
  • Throwable Class in Java with Examples

Packages in Java

  • Packages In Java
  • How to Create a Package in Java?
  • Java.util Package in Java
  • Java.lang package in Java
  • Java.io Package in Java
  • Java Collection Tutorial

Exception Handling in Java

  • Exceptions in Java
  • Types of Exception in Java with Examples
  • Checked vs Unchecked Exceptions in Java
  • Java Try Catch Block
  • Flow control in try catch finally in Java
  • throw and throws in Java
  • User-defined Custom Exception in Java
  • Chained Exceptions in Java
  • Null Pointer Exception In Java
  • Exception Handling with Method Overriding in Java
  • Multithreading in Java
  • Lifecycle and States of a Thread in Java
  • Java Thread Priority in Multithreading
  • Main thread in Java
  • Java.lang.Thread Class in Java
  • Runnable interface in Java
  • Naming a thread and fetching name of current thread in Java
  • What does start() function do in multithreading in Java?
  • Difference between Thread.start() and Thread.run() in Java
  • Thread.sleep() Method in Java With Examples
  • Synchronization in Java
  • Importance of Thread Synchronization in Java
  • Method and Block Synchronization in Java
  • Lock framework vs Thread synchronization in Java
  • Difference Between Atomic, Volatile and Synchronized in Java
  • Deadlock in Java Multithreading
  • Deadlock Prevention And Avoidance
  • Difference Between Lock and Monitor in Java Concurrency
  • Reentrant Lock in Java

File Handling in Java

  • Java.io.File Class in Java
  • Java Program to Create a New File
  • Different ways of Reading a text file in Java
  • Java Program to Write into a File
  • Delete a File Using Java
  • File Permissions in Java
  • FileWriter Class in Java
  • Java.io.FileDescriptor in Java
  • Java.io.RandomAccessFile Class Method | Set 1
  • Regular Expressions in Java
  • Regex Tutorial - How to write Regular Expressions?
  • Matcher pattern() method in Java with Examples
  • Pattern pattern() method in Java with Examples
  • Quantifiers in Java
  • java.lang.Character class methods | Set 1
  • Java IO : Input-output in Java with Examples
  • Java.io.Reader class in Java
  • Java.io.Writer Class in Java
  • Java.io.FileInputStream Class in Java
  • FileOutputStream in Java
  • Java.io.BufferedOutputStream class in Java
  • Java Networking
  • TCP/IP Model
  • User Datagram Protocol (UDP)
  • Differences between IPv4 and IPv6
  • Difference between Connection-oriented and Connection-less Services
  • Socket Programming in Java
  • java.net.ServerSocket Class in Java
  • URL Class in Java with Examples

JDBC - Java Database Connectivity

  • Introduction to JDBC (Java Database Connectivity)
  • JDBC Drivers
  • Establishing JDBC Connection in Java
  • Types of Statements in JDBC
  • JDBC Tutorial

Constructor chaining is the process of calling one constructor from another constructor with respect to current object. 

One of the main use of constructor chaining is to avoid duplicate codes while having multiple constructor (by means of constructor overloading) and make code more readable.

Constructor chaining can be done in two ways:   

  • Within same class : It can be done using this() keyword for constructors in the same class
  • From base class: by using super() keyword to call the constructor from the base class.

Constructor chaining occurs through inheritance . A sub-class constructor’s task is to call super class’s constructor first. This ensures that the creation of sub class’s object starts with the initialization of the data members of the superclass. There could be any number of classes in the inheritance chain. Every constructor calls up the chain till the class at the top is reached.

Why do we need constructor chaining?  

This process is used when we want to perform multiple tasks in a single constructor rather than creating a code for each task in a single constructor we create a separate constructor for each task and make their chain which makes the program more readable.   

Constructor Chaining within the same class using this() keyword:

Constructor Chaining In Java

Output:  

Rules of constructor chaining :  

  • The this() expression should always be the first line of the constructor.
  • There should be at-least be one constructor without the this() keyword (constructor 3 in above example).
  • Constructor chaining can be achieved in any order.  

What happens if we change the order of constructors? Nothing, Constructor chaining can be achieved in any order

Output: 

NOTE: In example 1, default constructor is invoked at the end, but in example 2 default constructor is invoked at first. Hence, order in constructor chaining is not important.   

Constructor Chaining to other class using super() keyword :

Note : Similar to constructor chaining in same class, super() should be the first line of the constructor as super class’s constructor are invoked before the sub class’s constructor. Alternative method : using Init block :  When we want certain common resources to be executed with every constructor we can put the code in the init block . Init block is always executed before any constructor, whenever a constructor is used for creating a new object. Example 1:

Output:   

NOTE: If there are more than one blocks, they are executed in the order in which they are defined within the same class. See the ex.  Example :  

Output :  

Feeling lost in the vast world of Backend Development? It's time for a change! Join our Java Backend Development - Live Course and embark on an exciting journey to master backend development efficiently and on schedule. What We Offer:

  • Comprehensive Course
  • Expert Guidance for Efficient Learning
  • Hands-on Experience with Real-world Projects
  • Proven Track Record with 100,000+ Successful Geeks

Please Login to comment...

  • School Programming
  • Vikramaditya Kukreja
  • jeevanmali1994
  • anikakapoor

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

VIDEO

  1. JAVA CONSTRUCTOR AND METHOD

  2. Demo qua Assignment Java 3

  3. Java Tutorial

  4. Constructor in JAVA

  5. constructor in java

  6. #32 Constructor in JAVA

COMMENTS

  1. Java Constructors

    A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes: Example Get your own Java Server Create a constructor:

  2. Java Constructors

    A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes. What are Constructors in Java? In Java, a Constructor is a block of codes similar to the method.

  3. Java Constructors (With Examples)

    A constructor in Java is similar to a method that is invoked when an object of the class is created. Unlike Java methods, a constructor has the same name as that of the class and does not have any return type. For example, class Test { Test () { // constructor body } } Here, Test () is a constructor.

  4. A Guide to Constructors in Java

    1. Introduction Constructors are the gatekeepers of object-oriented design. In this tutorial, we'll see how they act as a single location from which to initialize the internal state of the object being created. Let's forge ahead and create a simple object that represents a bank account. 2. Setting Up a Bank Account

  5. Best practices for assigning values passed through constructor

    Best practices for assigning values passed through constructor - JAVA Asked 6 years, 1 month ago Modified 6 years, 1 month ago Viewed 930 times 0 What is the quickest/most elegant way to assign values that were passed through a constructor? For example, if I have the class below:

  6. Java Constructor

    In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class is created. At the time of calling constructor, memory for the object is allocated in the memory. It is a special type of method which is used to initialize the object.

  7. Providing Constructors for Your Classes (The Java™ Tutorials

    This default constructor will call the no-argument constructor of the superclass. In this situation, the compiler will complain if the superclass doesn't have a no-argument constructor so you must verify that it does. If your class has no explicit superclass, then it has an implicit superclass of Object, which does have a no-argument constructor.

  8. Constructor in Java

    Here the output is clear because we are explicitly calling superclass constructor, so Java doesn't need to do any extra work from their side. Java Copy Constructor. Java copy constructor takes the object of the same class as an argument and creates a copy of it. Sometimes we need a copy of another object to do some processing.

  9. Constructors in Java

    Constructor is a block of code that initializes the newly created object. A constructor resembles an instance method in java but it's not a method as it doesn't have a return type. In short constructor and method are different (More on this at the end of this guide). People often refer constructor as special type of method in Java.

  10. Calling Methods and Constructors

    Calling Methods and Constructors Next in the Series Creating and Using Objects Calling Methods and Constructors Passing Information to a Method or a Constructor The declaration for a method or a constructor declares the number and the type of the arguments for that method or constructor.

  11. Constructors in Java (with examples)

    In this example, we use a private constructor to enforce encapsulation and a public factory method, create, for creating objects. The factory method ensures that the initial value is non-negative. B. Constructor vs. Static Factory Methods. In addition to constructors, Java allows the use of static factory methods for object creation.

  12. Constructor Makeover in Java 22

    In Java 22, the feature Statements before super() lets you execute code before calling super() in your derived class constructors, this() in your records or enums, so that you could validate the method parameters, or transform values, as required. This avoids creating workarounds like creating static methods and makes your code easier to read ...

  13. Constructor in Java

    The general syntax to declare a constructor in Java is as: Access modifiers_name class_name (formal_parameter_list) // constructor header. { // Constructor body which is a block of statements. // Here, we can initialize the values of instance variables. } The following example code defines a constructor in the class.

  14. Default Constructor in Java

    As a class-based object-oriented programming term, a constructor is a unique method used to initialize a newly created object (class). There are a few rules you must follow when creating constructors. These rules include: The name of the constructor must be the same as the class name. The constructor must have no return type.

  15. Variable Instantiation on Declaration vs. on Constructor in Java

    1. Introduction. There is uncertainty among Java developers on whether to initialize variables when they are declared or in a constructor. In this tutorial, we'll take a look at what happens when we initialize variables at their declaration or in a constructor. We'll try to point out some differences and similarities between them if they exist.

  16. Java Constructor

    Java constructors are invoked when their objects are created. It is named such because, it constructs the value, i.e., provide data for the object, i.e., they are used to initialize objects. Every class has a constructor when we don't explicitly declare a constructor for any java class the compiler creates a default constructor for that class ...

  17. Java programming Exercises, Practice, Solution

    Java is the foundation for virtually every type of networked application and is the global standard for developing and delivering embedded and mobile applications, games, Web-based content, and enterprise software. With more than 9 million developers worldwide, Java enables you to efficiently develop, deploy and use exciting applications and ...

  18. Constructor Chaining In Java with Examples

    Constructor chaining can be done in two ways: Within same class: It can be done using this () keyword for constructors in the same class From base class: by using super () keyword to call the constructor from the base class. Constructor chaining occurs through inheritance. A sub-class constructor's task is to call super class's constructor first.

  19. What's the difference between assignment operator and copy constructor?

    8 Answers Sorted by: 248 A copy constructor is used to initialize a previously uninitialized object from some other object's data. A (const A& rhs) : data_ (rhs.data_) {} For example: A aa; A a = aa; //copy constructor An assignment operator is used to replace the data of a previously initialized object with some other object's data.

  20. Java default constructor

    192 What exactly is a default constructor — can you tell me which one of the following is a default constructor and what differentiates it from any other constructor?