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.

Get hands-on with 1200+ tech skills courses.