course content

Course Content

Introduction to Java

ConstructorsConstructors

A constructor is a block of Java code similar to a method. Every Java class comes with a constructor. But we didn't write any such thing in our previous class. When we don't write a constructor for our class, the Java compiler creates a constructor. We call this the default constructor.

Do you remember how did we create a class in our last chapter?

java

Main.java

In this code, Person() actually calls the constructor of the person class. As we didn't write any constructor, the Java compiler creates a default constructor and calls for it.

Why are constructors used?

Constructors allow us to implement a certain functionality when we create an object from that class. Let's see an example.

java

Main.java

Here Person() is our constructor. Every time you create a person constructor will be created. As a result, you can see the output "Person is created" every time an object of Person is created.

There are three rules to be followed when you create a constructor:

  • Constructor names need to match class names exactly;
  • A constructor cannot have a return type that is specified explicitly;
  • Java constructors are not permitted to be abstract, static, final, or synchronized.

Constructors with parameters

The constructor in our previous example didn’t have any parameters. But it's possible to use parameters in the constructor.

Also, recall that in our last chapter. We first created the object and assigned the values to fields such as name and age as a second step. But with constructors, you can assign values to fields when the object is created.

Look at the following example:

java

Main.java

In this code, you assign a name and age to a person inside the constructor. You are passing values to those variables when you call the constructor with the Person("Mike",25).

There is one thing to be remembered, though. When you create a constructor for a class, the Java compiler no longer creates the default constructor. Therefore this class now only has one constructor, Person (String n, int a).

So you can only create an object by passing the requested values to the constructor. You can no longer create objects with the following code.

java

Main.java

However, having more than one constructor for the class is possible. We will talk about that in the constructor overloading chapter.

1. Which of the following are false statements about constructors?
2. Constructors can be ...

question-icon

Which of the following are false statements about constructors?

Select a few correct answers

question-icon

Constructors can be ...

Select a few correct answers

Section 2.

Chapter 3