Skip to main content
Published on

Constructors in Java

Share:

Introduction

Constructors are a fundamental aspect of object-oriented programming in Java. They play a crucial role in object initialization, ensuring that each object begins its lifecycle in a proper and defined state.

What is a Constructor?

A constructor in Java is a special block of code that is called when an object is instantiated. It has the same name as the class and can have different parameters or none at all. Its main purpose is to initialize the newly created object.

Characteristics of Constructors

  1. Class Name: The constructor must have the same name as the class.
  2. No Return Type: Constructors do not have a return type, not even void.
  3. Parameters: They can have parameters, allowing different constructors to exist for the same class.
  4. Automatic Call: They are called automatically when the object is created.

Types of Constructors

  1. Default Constructor: If you don't define any constructor in your class, Java will create a default constructor implicitly.
  2. Parameterized Constructor: This is the constructor that accepts arguments.

Practical Example

Let's look at an example that demonstrates the use of constructors in Java:

package com.caffeinealgorithm.programaremjava;

public class Main {
  public static void main(String[] args) {
    var person1 = new Constructors("Nelson", "Silva", 28);
    var person2 = new Constructors("Larissa", "Fernandes", 17);

    person1.information();
    person1.checkEntry();

    // Name: Nelson Silva
    // Age: 28
    // This person can enter the venue because they are over 18 years old.

    person2.information();
    person2.checkEntry();

    // Name: Larissa Fernandes
    // Age: 17
    // This person cannot enter the venue because they are under 18 years old.
  }
}
package com.caffeinealgorithm.programaremjava;

public class Constructors {
  String firstName = null, lastName = null;
  int age = 0;

  public Constructors(String firstName, String lastName, int age) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
  }

  public void information() {
    System.out.printf("Name: %s %s\n", firstName, lastName);
    System.out.printf("Age: %d\n", age);
  }

  public void checkEntry() {
    if (age >= 18)
      System.out.println("This person can enter the venue because they are over 18 years old.");
    else
      System.out.println("This person cannot enter the venue because they are under 18 years old.");
  }
}

Conclusion

Understanding constructors is essential for any Java programmer, as it is the first step in the life of an object. They ensure that objects are created and initialized correctly, providing a solid foundation for object-oriented programming.

Happy coding!