Page 268 - ComputerScience_Class_11
P. 268
Let us take an example:
Write a program that uses a copy constructor to create an object and display the sum of two
Program 13
integers.
1 class copyconstructor
2 {
3 int num1, num2, r;
4 copyconstructor(int n1, int n2)
5 {
6 num1=n1;
7 num2=n2;
8 }
9 void displaysum()
10 {
11 r=num1+num2;
12 System.out.println("Result "+r);
13 }
14 public static void main(String args[])
15 {
16 copyconstructor c_ob1=new copyconstructor(4,5);
17 copyconstructor c_ob2=c_ob1;
18 c_ob1.displaysum();
19 c_ob2.displaysum();
20 }
21 }
The output of the preceding program is as follows:
BlueJ: Terminal Window - Java
Options
Result 9
Result 9
9.12.3 Constructor Overloading
When a class has two or more constructors, it is known as Constructor Overloading. It depends on the number of
parameters or different types of parameters passed to the constructor to assign the data members of the class while
creating the objects.
For example,
class cons_over
{
int a,b;
cons_over()
{
a=0;
266 Touchpad Computer Science (Ver. 3.0)-XI

