Constructors

In this lesson, we will look at some common mistakes that are made while working with constructors.

Missing default constructor

Let’s recall some facts about constructors that we covered in the previous chapter:

📝 Note

  • If you do not define a constructor in your class, Java will provide a default constructor, that is, a constructor that has no parameters.
  • However, if every constructor that you define has parameters, Java will not define a default constructor for you. As a consequence, invoking a constructor without arguments will be illegal.

Let’s remove the definition of the default constructor from the class Square, as given in the previous chapter. We’ll add a main method, name the resulting class Square4, and place the result in the program given below.

The class still has a constructor, so the compiler will not supply a definition of a default constructor. An attempt to invoke a default constructor will result in an error message from the compiler, as you will see when you click the RUN button.

Press + to interact
/** Square4.java
A class of squares without a default constructor.
*/
public class Square4
{
private double side;
public Square4(double initialSide)
{
side = initialSide;
} // End constructor
public void setSide(double newSide)
{
side = newSide;
} // End setSide
public double getSide()
{
return side;
} // End getSide
public double getArea()
{
return side * side;
} // End getArea
public static void main(String[] args)
{
Square4 mySquare = new Square4(); // <--- Attempting to invoke a default constructor
System.out.println("My square's side and area are " +
mySquare.getSide() + ", " +
mySquare.getArea());
} // End main
} // End Square4

Because ...