Constructors
In this lesson, we will look at some common mistakes that are made while working with constructors.
We'll cover the following...
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.javaA class of squares without a default constructor.*/public class Square4{private double side;public Square4(double initialSide){side = initialSide;} // End constructorpublic void setSide(double newSide){side = newSide;} // End setSidepublic double getSide(){return side;} // End getSidepublic double getArea(){return side * side;} // End getAreapublic static void main(String[] args){Square4 mySquare = new Square4(); // <--- Attempting to invoke a default constructorSystem.out.println("My square's side and area are " +mySquare.getSide() + ", " +mySquare.getArea());} // End main} // End Square4
Because ...