Computer Applications
Answer
Constructor overloading is a technique in Java through which a class can have more than one constructor with different parameter lists. The different constructors of the class are differentiated by the compiler using the number of parameters in the list and their types. For example, the Rectangle class below has two constructors:
class Rectangle {
int length;
int breadth;
//Constructor 1
public Rectangle() {
length = 0;
breadth = 0;
}
//Constructor 2
public Rectangle(int l, int b) {
length = l;
breadth = b;
}
public static void main(String[] args) {
//Constructor 1 called
Rectangle obj1 = new Rectangle();
//Constructor 2 called
Rectangle obj2 = new Rectangle(10, 15);
}
}
Related Questions
Consider the given program and answer the questions given below:
class temp { int a; temp() { a=10; } temp(int z) { a=z; } void print() { System.out.println(a); } void main() { temp t = new temp(); temp x = new temp(30); t.print(); x.print(); } }(a) What concept of OOPs is depicted in the above program with two constructors?
(b) What is the output of the method main()?
Assertion: A class can have multiple constructors.
Reason: Multiple constructors are defined with same set of arguments.
- Assertion is true, Reason is false.
- Both assertion and Reason are false.
- Both assertion and Reason are true.
- Assertion is false, Reason is true.