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()?
Topic: Constructor overloading
Answer
(a) Polymorphism — specifically constructor overloading, which is compile-time (static) polymorphism. (b) 10 30
(a) One name behaving in several ways is polymorphism, literally "many forms". Here the class name temp serves as two different constructors, told apart by their parameter lists. Because the compiler decides which one to call from the arguments, this is compile-time or static polymorphism. Say both words — polymorphism AND constructor overloading — to be safe. (b) Object t is created with no argument, so the non-parameterised constructor runs and a = 10; t.print() displays 10. Object x is created with 30, so the parameterised constructor runs and a = 30; x.print() displays 30. Each object holds its own copy of a, so the two values do not interfere.