Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

Java Constructors

Java Constructors

In Java, a constructor is a special method responsible for initializing objects. It is invoked when an object of a class is created and can be utilized to assign initial values to object attributes:

Example

Generate a constructor:

// Create a Main class
public class Main {
  int x;  // Create a class attribute

  // Create a class constructor for the Main class
  public Main() {
    x = 5;  // Set the initial value for the class attribute x
  }

  public static void main(String[] args) {
    Main myObj = new Main(); // Create an object of class Main (This will call the constructor)
    System.out.println(myObj.x); // Print the value of x
  }
}

// Outputs 5

 

Keep in mind that the constructor name must align with the class name, and it cannot possess a return type such as void.

Additionally, remember that the constructor is invoked during object creation.

All classes inherently possess constructors; if you do not explicitly define a class constructor, Java automatically generates one for you. However, this precludes the ability to set initial values for object attributes.

Constructor Parameters

Constructors can accept parameters, allowing for attribute initialization.

In the given example, an int parameter y is introduced to the constructor. Within the constructor, we assign y to x (x = y). Upon calling the constructor, we provide an argument (5), which assigns the value 5 to x.

Example

public class Main {
  int x;

  public Main(int y) {
    x = y;
  }

  public static void main(String[] args) {
    Main myObj = new Main(5);
    System.out.println(myObj.x);
  }
}

// Outputs 5

As required, you can specify any quantity of parameters:

Example

public class Main {
  int modelYear;
  String modelName;

  public Main(int year, String name) {
    modelYear = year;
    modelName = name;
  }

  public static void main(String[] args) {
    Main myCar = new Main(1969, "Mustang");
    System.out.println(myCar.modelYear + " " + myCar.modelName);
  }
}

// Outputs 1969 Mustang