What Is a Constructor in Java and How Do You Use It?

In object-oriented programming, a constructor is a special function that you call to create an object. Constructors have several unique features which enable them to work.

In Java, you name a constructor after its class. A constructor is a method, defined in the class it applies to. Java constructors may use overloading to provide alternative behavior. Constructors in Java can also make use of inheritance to reuse code.

Why Do You Need Constructors Anyway?

Constructors are a mainstay of object-oriented programming, and Java is no exception. This example shows how you can define a basic Circle class with one data property and one method:

public class Circle {
public double radius;
public double area() { return 3.14159 * radius * radius; }
}

You can then create an instance of this class and interact with it:

Circle c = new Circle();
c.radius = 2;
System.out.println(c.area()); // 12.56636

But this is less convenient and robust than it could be. It’s good object-oriented practice to encapsulate data, protecting it from unauthorized access:

public class Circle {
private double radius;
public double area() { return 3.14159 * radius * radius; }
public void setRadius(double r) { radius = r; }
}

Now the calling code can use the setRadius method and not have to worry about its implementation details:

Circle c = new Circle();
c.setRadius(2);

Constructors offer an even better way of supplying data to an object when you create it. They are very often used for the initialization of properties, such as the radius here.

Examples of Simple Constructors

The most basic constructor is one with no arguments, that does nothing:

public class Circle {
public Circle() {}
}

See also: Learn How to Create Classes in Java

If you don’t define a constructor, Java will provide a default one that behaves in the same way.

Note a couple of things:

  1. The name of the constructor matches the class name.
  2. This constructor uses the public access modifier, so any other code can call it.
  3. A constructor doesn’t include a return type. Unlike other methods, constructors cannot return a value.

Constructors typically carry out some kind of initialization. Note that the above code does not initialize the value of radius. In this case, the language will automatically set it to zero. This class expects a user to use setRadius(). To use a more useful default than 0, you can assign it within the constructor:

public class Circle {
public Circle() { radius = 1; }
}

Circles created with this class will at least now have an actual area! The caller can still use setRadius() to provide a radius other than 1. But the constructor can be even friendlier:

public class Circle {
public Circle(double r) { radius = r; }
}

Now you can create circles with a specific radius right from birth:

Circle c = new Circle(2);
System.out.println(c.area()); // 12.56636

This is a very common use for constructors. You will often use them to initialize variables to parameter values.

Constructor Overloading

You can specify more than one constructor in a class definition:

public Circle() { radius = 1; }
public Circle(double r) { radius = r; }

This gives calling code a choice of how to construct objects:

Circle c1 = new Circle(2);
Circle c2 = new Circle();
System.out.println(c1.area() + ", " + c2.area()); // 12.56636, 3.14159

With a slightly more complex Circle, you can explore more interesting constructors. This version stores its position:

public class Circle {
public double x, y, radius;
public Circle() { radius = r; }
public Circle(double r) { radius = r; }
public Circle(double x, double y, double r) {
this.x = x; this.y = y; radius = r;
}

public double area() { return 3.14159 * radius * radius; }
}

You can now create a Circle with no arguments, a single radius, or x and y coordinates alongside the radius. This is the same kind of overloading that Java supports for any method.

Constructor Chaining

How about creating one Circle, based on another? This would give us the ability to copy Circles easily. Observe the following block:

public Circle(Circle c) {
this.x = c.x;
this.y = c.y;
this.radius = c.radius;
}

This will work, but it repeats some code unnecessarily. Since the Circle class already has a constructor that handles the individual properties, you can call that instead using the this keyword:

public Circle(Circle c) {
this(c.x, c.y, c.radius);
}

This is one form of constructor chaining, calling one constructor from another. It uses less code and helps centralize an operation rather than duplicating it.

Calling the Parent Constructor

The other form of constructor chaining occurs when a constructor calls a constructor of its parent class. This can be either explicit or implicit. To call a parent constructor explicitly, use the super keyword:

super(x, y);

Imagine a Shape class acting as the parent of the Circle:

public class Shape {
double x, y;
public Shape(double _x, double _y) { x = _x; y = _y; }
}

It handles common positioning for all shapes since this is functionality they all share. Now the Circle class can delegate position handling to its parent:

public class Circle extends Shape {
double radius;
public Circle(double r) { super(0, 0); radius = r; }
public Circle(double x, double y, double r) {
super(x, y);
radius = r;
}
}

Superclass construction is a very important aspect of inheritance in Java. The language enforces it by default if you don’t explicitly call super in your constructors.

Access Modifiers on Constructors

Constructors can include an access modifier in their signature. Like other methods, this defines which types of caller can access the constructor:

public class Test {
private static Test uniqueInstance = new Test();
private Test() { }
public static Test getInstance() {
return uniqueInstance;
}
}

This is a more complicated example, so take care to understand it:

  • The class is not abstract, so it is possible to instantiate from it.
  • The constructor is private so only this class itself can create a new instance.
  • Via a static property and method, the class exposes a single, unique instance of itself to callers.

Use Constructors in Java to Create Objects

Constructors are vital to object-oriented programming. They allow you to create objects, which is essential!

In Java, constructors look like other methods and work in much the same way. You should remember the special rules around default constructors, overloading, and constructor chaining. If constructors are new to you, you might want to read up on the other core Java concepts you should learn when getting starting.

Source: makeuseof.com

Related posts

The Best Google Pixel 8a Cases

The 9 Best DALL-E 3 Editing Prompts

You Can Use Android Apps on Your Chromebook: Here’s How