Constructors in Java:Your Path to Efficient Coding

Constructors in Java

  • A constructor in Java, could be a extraordinary type of method that’s utilized to initialize objects.
  • A constructor in Java called naturally when an object of a class is made.
  • Constructors help in initializing the object’s state (i.e., assigning values to the areas of the object) when it is made.

Key Focuses about Constructors in Java:

  • A constructor has the same name as the class.
  • It does not have a return type, not indeed void.
  • It is naturally invoked when an object is made utilizing the new keyword.
  • Constructors are utilized to initialize the object’s state (fields).
Types of Constructors in Java
Types of Constructors in Java

Types of Constructors in Java:

  1. Default Constructor (no-argument Constructor)
  2. Parameterized Constructor(argument Constructor)
1. Default Constructor (No-argument Constructor)
  • A default constructor might be a constructor that’s automatically given by Java in case no constructors are characterized explicitly inside the class.
  • It has no parameters and is utilized to create an object with default values (such as 0, null, or false depending on the data type).
  • Inside the event that you just essentially do not characterize any constructor in your class, Java will automatically give a default constructor.

Example of Default Constructor:

class Car {
String brand;
int year;

// Default constructor
public Car() {
brand = "Unknown"; // Default value
year = 0; // Default value
}

public void displayDetails() {
System.out.println("Brand: " + brand + ", Year: " + year);
}
}

public class Main {
public static void main(String[] args) {
Car car = new Car(); // Calls the default constructor
car.displayDetails(); // Output: Brand: Unknown, Year: 0
}
}

  • In this example, the Car class includes a default constructor that initializes brand to “Unknown” and year to 0. When we make a new object utilizing new Car(), this constructor is called subsequently.
2. Parameterized Constructor
  • A parameterized constructor can be a constructor that grants passing parameters to initialize an object with specific values at the time of creation.
  • The constructor takes arguments to initialize the fields of the class.

Example of Parameterized Constructor:

class Car {
String brand;
int year;

// Parameterized Constructor
public Car(String brand, int year) {
this.brand = brand; // Initialize with provided values
this.year = year; // Initialize with provided values
}

public void displayDetails() {
System.out.println("Brand: " + brand + ", Year: " + year);
}
}

public class Main {
public static void main(String[] args) {
Car car = new Car("Toyota", 2024); // Calls parameterized constructor
car.displayDetails(); // Output: Brand: Toyota, Year: 2024
}
}

  • In this example, the Car class includes a parameterized constructor that takes two arguments, brand and year.  When making a new Car object, the values for brand and year are given to the constructor, which initializes the object in like manner.

Constructor Overloading

  • Java supports constructor overloading, which implies you’ll be able have different constructors within the same class with diverse parameters.
  • The constructor is chosen based on the arguments passed during object creation.

Example of Constructor Overloading:

class Car {
String brand;
int year;

// Constructor 1: Default constructor
public Car() {
brand = "Unknown";
year = 0;
}

// Constructor 2: Parameterized constructor
public Car(String brand, int year) {
this.brand = brand;
this.year = year;
}

public void displayDetails() {
System.out.println("Brand: " + brand + ", Year: " + year);
}
}

public class Main {
public static void main(String[] args) {
// Calling default constructor
Car car1 = new Car();
car1.displayDetails(); // Output: Brand: Unknown, Year: 0

// Calling parameterized constructor
Car car2 = new Car("Honda", 2022);
car2.displayDetails(); // Output: Brand: Honda, Year: 2022
}
}

  • In this case, the Car class has two constructors: one may be a default constructor with no parameters, and the other may be a parameterized constructor with two parameters (brand and year).
  • Java chooses the fitting constructor based on the arguments passed.

Constructor vs Method: Key Differences

Whereas both constructors and methods are utilized to characterize behavior in a class, there are critical contrasts:

AspectConstructorMethod
NameSame as the class nameCan be any name (except void)
Return TypeNo return type (not even void)Must have a return type (can be void)
PurposeInitializes objectsDefines the behavior of the object
Called byAutomatically when an object is createdExplicitly called by an object or class
InheritanceCannot be inheritedCan be inherited

 

Constructor Chaining

  • In Java, constructor chaining is the method of calling one constructor from another constructor within the same or distinctive class.
  • Ordinarily done utilizing the this() keyword (for calling another constructor inside the same class) or the super() keyword (for calling a constructor inside the parent class).

Example of Constructor Chaining using this():

class Car {
String brand;
int year;

// Constructor 1: Default constructor
public Car() {
this("Unknown", 0); // Calling parameterized constructor from the default constructor
}

// Constructor 2: Parameterized constructor
public Car(String brand, int year) {
this.brand = brand;
this.year = year;
}

public void displayDetails() {
System.out.println("Brand: " + brand + ", Year: " + year);
}
}

public class Main {
public static void main(String[] args) {
Car car1 = new Car(); // Calls the default constructor, which calls the parameterized constructor
car1.displayDetails(); // Output: Brand: Unknown, Year: 0

Car car2 = new Car("Ford", 2023); // Calls parameterized constructor directly
car2.displayDetails(); // Output: Brand: Ford, Year: 2023
}
}

  • In this example, the default constructor (Car()) calls the parameterized constructor (Car(String brand, int year)) using this().

Example of Constructor Chaining Using super() (for parent class constructor):

class Vehicle {
String type;

// Constructor in parent class
public Vehicle(String type) {
this.type = type;
}

public void displayType() {
System.out.println("Vehicle Type: " + type);
}
}

class Car extends Vehicle {
String brand;

// Constructor in child class
public Car(String brand) {
super("Car"); // Calling the parent class constructor
this.brand = brand;
}

public void displayDetails() {
displayType();
System.out.println("Brand: " + brand);
}
}

public class Main {
public static void main(String[] args) {
Car car = new Car("Toyota");
car.displayDetails(); // Output: Vehicle Type: Car, Brand: Toyota
}
}

  • In this example, the Car class uses super() to call the constructor of the parent class (Vehicle) and initialize the type field.

Key Focuses Keep in mind about Constructors in Java:

  • Default Constructor: In case no constructors are characterized, Java gives a default constructor that initializes members with default values.
  • Parameterized Constructor: You’ll be able characterize constructors that acknowledge parameters to initialize the object with particular values.
  • Constructor Overloading: You can have multiple constructors with different parameter lists.
  • Constructor Chaining: You can call one constructor from another using this() (for same-class constructor calls) or super() (for parent class constructor calls).

Leave a Comment