What is Constructor Injection?

Constructor Injection is used when a specific class requires one or more dependencies. In such a case, we would supply these dependencies as a parameter of the class’s constructor.

Whenever we create a new class, we come across variables and methods.

In a class, the variables are private and we need methods to set or get them. The process where these variables are set using a constructor is called constructor injection.

As an example, let’s create the class Shape. This class can have polygons, triangles, squares, circles, etc.

Define the new class:

public class Shape {
}

Now, define a variable to define the type of Shape. This variable will need get and set methods as well:

public class Shape {

private String type;

public String gettype(){
return type;
}

public void settype(String type){
this.type = type;
}

}

We are using getters and setters to set and get the data. However, there is a better way to set the data using constructors:

public class Shape {
private String type;

public Shape(String type)
{
this.type = type;
}

}

In this way, you can easily set the variables when the class is called – you do not need a special function just to set the data.

Next, you may want to create another variable.

You can edit the old constructor, or even create a new one with two parameters.

public class Shape {
private String type;
private int length;

public Shape(String type)
{
this.type = type;
}

public Shape(int length)
{
this.length = length;
}

public Shape(String type, int length)
{
this.type = type
this.length = length;
}

}

This way, you can make use of constructors to work with classes.

class Shape{
String type;
int length;
public Shape(String type)
{
this.type = type;
}
public Shape(int length)
{
this.length = length;
}
public Shape(String type, int length)
{
this.type = type;
this.length = length;
}
public static void main( String args[] ) {
Shape myObj = new Shape("Triangle", 20);
System.out.println(myObj.length);
System.out.println(myObj.type);
}
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved