Java Constructors Complete Tutorial

In this section we will learn what the constructors are and how to use them in Java.

Java What Is Constructor?

Constructors are methods in the class that do not have any return value (not even `void`) and their name is exactly the same as the name of the owner class.

Consider a class named `Employee`. Inside this class we have three fields named `name` and `lastName` and `id`:

public class Employee {
    private String name; 
    private String lastName;
    private int id;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
}

Here, as you can see, there are setters methods like `setName()`, `setId()` in order to set the values for the member variables of the class.

So when we create an object from this class, we can call these methods and initialize the member variables.

Example:

public class Simple {

    public static void main(String[] args) {
        Employee emp = new Employee();
        emp.setId(1002);
        emp.setName("John");
        emp.setLastName("Doe");
    }
}

In this example, when we created a new object from the `Employee` class, we used 3 set-methods of the object to set the initial value of the `id`, `name` and `lastName` members of the object, respectively.

But wouldn’t be easier if we could initialize these variables right where the object is being created?

This is where constructors come in!

How to define a constructor in Java? (Constructor syntax)

Access-specifier ClassName(){/*...*/}

By default, if we don’t create a constructor in a class, the compiler would automatically create one for us. This auto-created constructor does not have any parameter and its body is empty.

As a matter of fact, when we create an object from a class, we use `()` on the right side of the name of the class, right? What happens here is that we’re calling that empty constructor with no-parameter.

Note: in the Java default constructor section, we’ll explain this constructor in more details.

Access Modifiers of Constructors in Java

Either of `public`, `private` and `protected` access specifiers can be used for constructors.

Note: if the access specifier of a constructor is set to `private` we will not be able to create an object from that class.

Example: creating constructor in Java

Now if we want to create our own constructor in the Employee class, we could go like this:

public class Employee {
    private String name;
    private String lastName;
    private int id;

    public Employee(int id, String name, String lastName){
        this.id = id;
        this.name = name;
        this.lastName = lastName;
    }
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
}

Take a look at the constructor here:

public Employee(int id, String name, String lastName){
        this.id = id;
        this.name = name;
        this.lastName = lastName;
}


As you can see, the name of the constructor is the same as the name of the class. This constructor takes 3 arguments and assigns these arguments to the member variables of the object that is created via calling this constructor.

Now that we have such constructor in this class, we can use it when creating objects from the class.

Example:

public class Simple {

    public static void main(String[] args) {
        Employee emp = new Employee(10, "John","Doe");
        System.out.println(emp.getId());
        System.out.println(emp.getName());
        System.out.println(emp.getLastName());
    }
}

Output:

10

John

Doe

In this example, instead of using an empty pair of parentheses which represents the empty constructor, we used the one that we’ve just created and set 3 arguments to be assigned to the 3 member variables.

Java Default constructor note

The moment we create a constructor in a class, the default constructor is gone and we can’t use it anymore, unless we explicitly define it again in the class.

For example, if we attempt to create an object from the default constructor, we will get a compile time error because there’s no such constructor in the class anymore:

public class Simple {

    public static void main(String[] args) {
        Employee emp = new Employee();
        System.out.println(emp.getId());
        System.out.println(emp.getName());
        System.out.println(emp.getLastName());
    }
}

Output:

Error:(6, 24) java: constructor Employee in class tuto.Employee cannot be applied to given types;

required: int,java.lang.String,java.lang.String

found: no arguments

reason: actual and formal argument lists differ in length

Difference between constructor and method in Java

In short, constructors are used for when we want to create an object from a class in order to initialize the fields of a class and essentially the initial works on what needs to be done when an object is being created.

On the other hand, methods are used for creating the tasks and functionalities that are expected from an object at runtime. We may or may not use these methods throughout its lifetime.

More to Read

Java Default Constructor

Java Chaining Constructor

Java Constructor Overloading

 

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies