Page 263 - ComputerScience_Class_11
P. 263
8 }
9 void add(sum ob1, sum ob2)
10 {
11 this.a=ob1.a+ob2.a;
12 this.b=ob1.b+ob2.b;
13 s=this.a+this.b;
14 }
15 void show()
16 {
17 System.out.println("The result is "+s);
18 }
19 public static void main(String[] args)
20 {
21 sum t1=new sum();
22 sum t2=new sum();
23 sum t3=new sum();
24 t1.input(4,3);
25 t2.input(2,1);
26 t3.add(t1,t2);
27 t3.show();
28 }
29 }
The output of the preceding program is as follows:
BlueJ: Terminal Window - Java
Options
The result is 10
Here,
a. void input (int a, int b): The parameters and the data members are of the same name, which creates an identity
problem for the compiler. The compiler cannot understand which values of ‘a’ and ‘b’ are to be considered – the
parameters mentioned here or the data members. So, when ‘this’ keyword is used with the data members, the
compiler clearly understands the values of ‘a’ and ‘b’ to be picked up for calculation.
b. void add (sum ob1, sum ob2): The objects in the parameters have the same instance variables that are there
in the current object. So, to differentiate between them, ‘this’ keyword is used, where ‘this’ refers to the
current object.
9.12 CONSTRUCTOR
All the instance variables need to be initialised as soon as the object is created. This is done by the method
constructor.
A constructor is a member function that has the same name as that of a class and is used to initialise the instance
variables of the objects that are created.
Methods and Constructors 261

