Mark As Completed Discussion

Default Constructor

Whenever you instantiate an object, you are calling a method (notice the double parentheses after new ClassName). This method is the default constructor. Default constructors do not take any parameters and do not need to be explicitly defined by the user. However, you can override the default constructor if you want. For example, if we want a rectangle to be 1x1 initially, then we will need to override the default constructor.

TEXT/X-JAVA
1// Rectangle.java
2public class Rectangle extends Shape {
3    protected int height;
4    protected int width;
5
6    // Overriding default constructor
7    public Rectangle() {
8        this.height = 1;
9        this.width = 1;
10    }
11
12    // Custom Constructor
13    public Rectangle(int height, int width) {
14        this.height = height;
15        this.width = width;
16    }
17
18    // Rest of the methods and Attributes
19}