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()?
Name the following:
(a) Method with the same name as of the class and is invoked every time an object is created.
(b) Keyword to access the classes of a package.