How to Create a Constructor for a Class in Java


In this article, we show how to create a constructor for a class in Java.

A constructor is a method that is automatically called when an object is instantiated.

The reason we create a constructor is to initalize a newly created object.

There are a few rules for creating constructors in Java.

One of the first rules is that the constructor must be the same name as the class name.

Another rule is that the doesn't have a return type. So you don't call a constructor void method_name or int method_name. It doesn't have a return type. It simply exists to initialize a newly instantiated object. So there is no return type at all specified in the definition (when you are defining it).

So below in the code is an example constructor. I create a class called students.

Beneath this is the constructor for the Students class.

So above, we have a class named students.

In this students class, we have declared 3 variables, name, gender, and age.

Right below this, we create a constructor for the class. This constructor, as you can see, has the same name as the class name. It is a requirement in Java for a constructor to have the same name as the class. Notice also how we didn't declare any return type for the constructor. A constructor does not have a return type.

The constructor accepts 3 arguments (or parameters). The String n, String g, and int a.

Inside of the constructor, which like all methods is inside curly braces, we set the name variable equal to n, the gender variable equal to g, and the age variable equal to a. This sets the values we passed into the object properties.

So this is all that is needed to create a constructor in Java.

If you open up a project in Java and put this code as one of the classes and then create a test page so that you can test this class, we can instantiate an object passing these 3 parameters into it.

So open up a project put the code above in the page and open up a second page that can function to test out this class and constructor in this class.

Say, if we open up a page,

Writing the code below, we can test the constructor and output the newly instantiated object.

So this test page allows us to instantiate an object of the students class and test out the constructor in the students class.

Since the constructor accepts 3 parameters, the student's name, gender, and age, we create a new object student1 with the values "Bob", "Male", and 13.

We then output these object properties.

And this is how a constructor can be created in Java.

Running the code above gives the following output below.

Java Output

Student's name: Bob

Student's gender: Male

Student's age: 13

HTML Comment Box is loading comments...