Home

 › 

Articles

 › 

Understanding Constructors In Java, With Examples

php vs. java

Understanding Constructors In Java, With Examples

When you’re working with Java, you’ll often want to use constructor functions. They’re useful for many things, including encapsulation, inheritance, function overloading, and making sure an object’s initial state is valid. In this article, we’ll explore how constructors in Java work, and how to use them well.

What Are Constructors in Java?

Constructors are found in many object-oriented programming (OOP) languages, not just Java. They mostly perform the same functions wherever they’re found, mainly to initialize the state of a class object. In this way, they’re pivotal in the creation of an object, which is why they’re known as constructors. These methods differ from typical methods, in that they don’t have a return type, and have the same name as the class they belong to.

Why Are Constructors in Java Used?

Constructors are used to initialize an object’s data, to avoid having to do this yourself every time. They’re also used for enforcing encapsulation because they prevent the object from being changed from outside the program. Both constructor overloading and constructor chaining are also possible. Overloading is where we have multiple constructors within a class, which can create objects with different parameters. Chaining, however, is where a constructor in one class calls a constructor in its superclass, or parent class. Chaining helps to avoid code duplication, whereas overloading makes code more flexible.

Constructors in Java: Types and Applications

The 3 main types of constructors in Java are default, copy, and parameterized constructors. It’s worth noting these are all defined within the class in Java. Let’s take a brief look at each of these in more detail.

Default constructors

As you may be able to guess, the default constructor is created when we don’t explicitly provide a constructor. In this case, the compiler automatically generates a constructor. For example, see this code:

public class Defaultconstructor {
    private String name;
    private int age;

    public Defaultconstructor() {
        name = "Unknown";
        age = 0;
    }

    public void displayInfo() {
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
    }

    public static void main(String[] args) {
        Defaultconstructor obj = new Defaultconstructor();

        obj.displayInfo();
    }
}

First, we declare the class “Defaultconstructor”, with private variables “age” and “name”. The default constructor “Defaultconstructor” is then declared, which initializes the “name” and “age” variables to “Unknown” and “0” respectively. We then use the “displayInfo” method to print the output. The code is executed via the main function, which calls the default constructor. This creates an object instance, after which the “displayInfo” method is called. We can see the results in the image that follows.

Constructors in Java
The result of using a constructor illustrated.

Copy constructors

Copy constructors in Java are a little different to other languages such as C++. This is because there is no default copy constructor implementation in Java – it’s not created automatically. The syntax for copy constructors is slightly different between Java and C++, as well as the creation. While a copy constructor in C++ uses a reference to an object as a parameter, Java takes an instance of the same class as a parameter. In both cases, the values of the object are copied to the new object. To see how copy constructors in Java can be used, consider this code:

public class Defaultconstructor {
    private String name;
    private int age;

    public Defaultconstructor() {
        name = "Unknown";
        age = 0;
    }

    public Defaultconstructor(Defaultconstructor other) {
        this.name = other.name;
        this.age = other.age;
    }

    public void displayInfo() {
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
    }

    public static void main(String[] args) {
        Defaultconstructor obj1 = new Defaultconstructor();
        obj1.displayInfo();

        Defaultconstructor obj2 = new Defaultconstructor(obj1); // Using the copy constructor
        obj2.displayInfo();
    }
}

Using the same code as before, we’ve added a copy constructor, which takes an instance and copies the “name” and “age” values to the new object, “obj2”. This information is displayed using “obj2.displayInfo()”. Essentially, this gives us the same output as before but twice, as we can see in the image.

You can also use the clone() and copy() methods to copy object data, depending on your needs. These can offer more flexibility but don’t use a constructor.

Constructors in Java
Using a copy constructor is illustrated with a program.

Parameterized constructors

In contrast to a default constructor, a parameterized constructor takes parameters. This allows us to initialize the member variables with whatever values we like. For example, look at this code:

public class Defaultconstructor {
    private String name;
    private int age;

    public Defaultconstructor(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public void displayInfo() {
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
    }

    public static void main(String[] args) {
        Defaultconstructor obj1 = new Defaultconstructor("John Doe", 25);
        obj1.displayInfo();

        Defaultconstructor obj2 = new Defaultconstructor(obj1.name, obj1.age);
        obj2.displayInfo();
    }
}

Instead of a copy constructor, we’ve declared a parameterized constructor instead that takes the “name” and “age” variables. Two objects, “obj1” and “obj2”, are created using the constructor, and the values of the first object are passed to the second object. This can be seen in the output.

Constructors in Java
Using a parameterized constructor allows us to initialize the value of variables.

What Makes Constructors Different to Other Methods?

Constructors are similar to other methods in some ways, but on the whole, they’re very different. This is a quick rundown of how.

  • Constructors have no return type
  • they have the same name as the class they’re part of
  • While constructors are automatically called after using the new keyword, ordinary methods have to be called explicitly
  • Constructors are mostly used to initialize an object.

Wrapping Up

Overall, constructors in Java are a useful technique for initializing objects, making sure they’re robust, and allowing flexibility in the creation of multiple instances with different values. Constructors can be used with each other or can call one another, this being overloading or chaining. There are 3 main types of constructors in Java, which are default, copy or parameterized constructors. Knowing how to use all of these will help you work with Java better.

Frequently Asked Questions

What are constructors in Java?

Constructors are special methods used when creating objects to initialize their variables with either default or specific values. Constructors can also be used to copy values of an object to a newly created object. These are called copy constructors.

How do constructors in Java differ to constructors in C++?

The syntax for using constructors is different, and Java has no built-in copy constructor. The base class constructor call is also more strict in Java, whereas this can be modified in C++. Java also uses automatic garbage collection in place of explicit destructor functions.

How does inheritance make use of constructors?

Since derived classes can inherit properties from their parent class, the constructor in the parent class is called first to initialize the object. This is done using super(), and whatever arguments have been specified. If none have, then a default constructor is used.

Why are base class constructors called first?

This is done to make sure the initial state of the object is valid before any modifications occur. The constructors are then propagated through the chain of classes, and executed correctly.

What's the difference between default and parameterized constructors?

Default constructors are created if no instructions are explicitly defined. They have no parameters or arguments, and initialize an object with default values. On the other hand, parameterized constructors accepts parameters as arguments, and initializes objects with specific values. Generally, these offer more flexibility and customization.

What are constructor overloading and constructor chaining?

Constructor overloading refers to when multiple constructors are used to create objects with different values. Chaining, however, is when a constructor from one class is called by a constructor in another class. This is done to avoid code duplication and allow code to be reusable.

Does Java use inline and external constructors?

No, Java does not use inline and external constructors like C++.  Constructors in Java are always explicitly defined within the class itself, rather than from outside. Therefore, these can be thought of as always inline.

Are constructors private or protected?

Constructors in Java can be either private, protected or public. Where private constructors can only be accessed from within the class, protected constructors can be accessed from within the same class or derived classes.

To top