DEV Community

Cover image for Java Constructors - [Java OOP #2]
rachel
rachel

Posted on

Java Constructors - [Java OOP #2]

In the previous article of this Java OOP Series, I briefly mentioned how we can use a constructor to initialise objects. In this article, we will further discuss about the different types of constructors.

Recap

A Constructor is a method that is used to initialise objects. It is called once whenever an object of a class is created.

  • Unlike Java methods, a constructor must have the same name as the class and it does not have a return type.

  • Take note that it is not necessary to write a constructor for a class as the Java compiler creates a default constructor if there isn't any in the class.

Types of constructors

Java constructors can be categorised into no-argument constructors or parameterised constructors. The default constructor is a no-argument constructor.

  • No-argument constructors

A no-argument constructor is a constructor that does not have any parameters.

class Student {
    // fields
    private String name;

    // constructor
    Student() {
        name = "Alice"; 
    }

    public static void main(String[] args) {
        // constructor is invoked while
        // creating an object of the Student class
        Student newStudent = new Student();
        System.out.println("The name is " + newStudent.name);
    }
}    
Enter fullscreen mode Exit fullscreen mode
  • Parameterised constructors

Parameterised constructors are constructors that takes one or more parameters.

class Student {
  String name;
  int age;

  Student(String name, int age) {
    this.name = name;
    this.age = age;
    System.out.println(name + " is " + age + " years old.");
  }

  public static void main(String[] args) {
    Student Student1 = new Student("Bob", 12);
    Student Student2 = new Student("Krystal", 14);
  }
}
Enter fullscreen mode Exit fullscreen mode

The this keyword is used to avoid ambiguity because Java compiler cannot differentiate between the variable and parameter if they both have same names. this keyword will refer to the current object inside the constructor.

  • Default constructors

If we do not create any constructors, the Java compiler creates a default constructor during the execution of the program. It initialises any uninitialised instance variables with default values:

Variable Type Default Value
boolean false
int
byte
short
0
float
double
0.0
char \u0000
Reference types null
class Example {

  int a;
  boolean b;

  public static void main(String[] args) {
    // call the constructor
    Example obj = new Example();

    System.out.println("Default Value:");
    System.out.println("a = " + obj.a);
    System.out.println("b = " + obj.b);
  }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)