Java
Constructor overloading
Learn multiple constructors in the same class.
Constructor overloading
A class can have more than one constructor; this is called overloading. Each constructor must have a different parameter list: the number, type or order of parameters can vary. Which constructor is called depends on the values in the parentheses.
Example: class Rectangle { int w, h; Rectangle() { w = 0; h = 0; } Rectangle(int s) { w = s; h = s; } }. Here two constructors exist. new Rectangle() calls the first, new Rectangle(5) the second. Overloading provides flexible instantiation; it prepares the instance with different values in different situations.
Which constructor is called?
Java decides which constructor to run by looking at the number and types of arguments in the call. If exactly one constructor matches, it calls it. If none matches or the match is ambiguous, a compile error occurs.
Example: new Rectangle() calls the no-arg constructor, new Rectangle(5) the single-parameter one. new Rectangle(5, 3) works only if a two-parameter constructor exists. Type conversion is also considered; new Rectangle(5.0) does not match an int parameter.
Exercise Add two constructors to Rectangle
Define a class named Rectangle. Add int w and int h fields. Write two constructors: the first takes no arguments and sets both to zero; the second takes an int s and assigns s to both w and h. In main call both constructors and print the w fields on separate lines.
Show example solution
class Rectangle {
int w;
int h;
Rectangle() {
w = 0;
h = 0;
}
Rectangle(int s) {
w = s;
h = s;
}
public static void main(String[] args) {
Rectangle a = new Rectangle();
Rectangle b = new Rectangle(5);
System.out.println(a.w);
System.out.println(b.w);
}
}
Test yourself
-
Which is true about overloading?
- Two constructors must have the same parameter list
- Constructors must have return types
- A class must have only one constructor
- Two constructors must have different parameter lists
Show answer
Two constructors must have different parameter lists — In overloading, each constructor must have a different parameter list.
-
Complete the second constructor
class Rectangle {
int w, h;
Rectangle() { w = 0; h = 0; }
____(int s) { w = s; h = s; }
}
Show answer
class Rectangle {
int w, h;
Rectangle() { w = 0; h = 0; }
Rectangle(int s) { w = s; h = s; }
}
-
Match call to constructor
- new Rectangle()
- No-arg constructor
- new Rectangle(5)
- Single-param constructor
- new Rectangle(5, 3)
- Two-param constructor
Next lesson: this()