In Java, methods are used to store blocks of code that perform a specific action. When you’re working with methods, you may encounter a concept called constructors
.
Constructors are special methods used to initialize objects in Java. Constructors are called when the object of a class is created, and are used to set initial values for an object.
This tutorial will discuss, with examples, the basics of Java constructors and how to use constructors in your code. By the end of reading this tutorial, you’ll be an expert at using Java constructors to initialize objects.
Java Constructors
Constructors initialize a newly created object before it is used in a program. So, for instance, a constructor called Supplier would create an object with the default attributes of a supplier.
Constructors have the same name as their class and do not return any value. Here is an example of a constructor in Java:
class Supplier { Supplier() { // Code here } }
In this example, we have declared a constructor called Supplier
, which has the same name as our class. In addition, our constructor does not have any return type—such as void—which is what distinguishes it from other types of methods.
There are two rules you need to know when you’re declaring a constructor. First, the name of a constructor must match the name of the class in which the constructor is declared exactly. Second, constructors cannot return values.
How to Create a Java Constructor
There are two types of Java constructors: no-arg constructors and parameterized constructors. Let’s break down how to create a constructor using both these types.
No-arg Constructors
Suppose we are operating a grocery store and we want to create a program that stores details about our main supplier for cheese. This program should include a constructor which stores the supplier’s information, and should also print out those values to the console.
Here’s the code we would use to create this program:
class MainCheeseSupplier { private String name; private String address; private int discountRate; private String payDate; private MainCheeseSupplier() { name = "J. Acker Dairy"; address = "1600 Johnson Ave. San Francisco 94127"; discountRate = 2; payDate = "Last day of the month."; } public static void main(String[] args) { MainCheeseSupplier jadairy = new MainCheeseSupplier(); System.out.println("Name: " + jadairy.name); System.out.println("Address: " + jadairy.address); System.out.println("Discount rate: " + jadairy.discountRate); System.out.println("Pay date: " + jadairy.payDate); } }
Our code returns:
Name: J. Acker Dairy Address: 1600 Johnson Ave. San Francisco 94127 Discount rate: 2 Pay date: Last day of the month.
First, we have defined a class called MainCheeseSupplier
which holds the code for our program. Then we initialized four private variables—name
, address
, discountRate
, and payDate
—which we use to store information about our main cheese supplier.
Once we have declared those variables, we create a constructor called MainCheeseSupplier
which initializes them with default values. Then, in our main program, we initialize an instance of our constructor by using this code:
MainCheeseSupplier jadairy = new MainCheeseSupplier();
This code assigns the variable jadairy
a new instance of the MainCheeseSupplier
object. Then, we print out each value held in jadairy to the console by referencing the jadairy
variable and the attribute we want to access.
This is an example of a no-arg constructor. Because our constructor does not accept any parameters, we refer to it as no-arg.
Parameterized Constructor
However, there may be a case where you want to pass arguments through a constructor.
Let’s return to the grocery store. Say that we want to define the values of our main cheese supplier details in our main program and assign them to our constructor when the main program has started executing.
We may want to do this because we are initializing multiple suppliers with different values, or because we do not want to assign specific values to the constructor.
If we pass arguments through a constructor, we call it a parameterized constructor.
We could pass a parameter list through a constructor like this:
class MainCheeseSupplier { String name; String address; int discountRate; String payDate; public MainCheeseSupplier(String supplierName, String supplierAddress, int supplierDiscountRate, String supplierPayDate) { name = supplierName; address = supplierAddress; discountRate = supplierDiscountRate; payDate = supplierPayDate; } public static void main(String[] args) { MainCheeseSupplier jadairy = new MainCheeseSupplier("J. Acker Dairy", "1600 Johnson Ave. San Francisco 94127", 2, "Last day of the month."); System.out.println("Name: " + jadairy.name); System.out.println("Address: " + jadairy.address); System.out.println("Discount rate: " + jadairy.discountRate); System.out.pintln("Pay date: " + jadairy.payDate); } }
Our code returns:
Name: J. Acker Dairy Address: 1600 Johnson Ave. San Francisco 94127 Discount rate: 2 Pay date: Last day of the month.
As you can see, the output of our code in this example is the same as it was in our first example. However, there is one big difference in our code: instead of initializing the values of our constructor in the constructor itself, we pass them as parameters when we declare an instance of the constructor.
In the above example, the MainCheeseSupplier
constructor accepts four parameters: supplierName
, supplierAddress
, supplierDiscountRate
, and supplierPayDate
. When we initialize an instance of the MainCheeseSupplier
constructor, we pass values through these parameters, which are then read by our constructor. Here’s the code we use to initialize an instance of the constructor:
MainCheeseSupplier jadairy = new MainCheeseSupplier("J. Acker Dairy", "1600 Johnson Ave. San Francisco 94127", 2, "Last day of the month.");
Then, we print out the contents of the values we stored in the MainCheeseSupplier
constructor.
Conclusion
Java constructors are special methods used to initialize objects. Constructors are called when an object of a class is created and can be used to set initial values for an object’s attributes.
This tutorial discussed, with reference to examples, how to create and work with constructors in Java. Now you’re ready to start using Java constructors like an expert!
About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.
"Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!"
Venus, Software Engineer at Rockbot