Page 235 - Cs_withBlue_J_C11_Flipbook
P. 235

Let us take the following example for the array arr:
                    int arr[]=new int[10];

                     9.11 this KEYWORD
                 The ‘this’ keyword indicates the current object of the class being referred to. It is generally used to distinguish between
                 the class attributes and parameters of a class, when they have the same names.
                 Let us take the following example:
                    class sum
                    {
                        int a, b, s;
                        void input(int a, int b)
                        {
                            this.a=a;
                            this.b=b;
                        }
                        void add(sum ob1, sum ob2)
                        {
                            this.a=ob1.a+ob2.a;
                            this.b=ob1.b+ob2.b;
                            s=this.a+this.b;
                        }
                        void show()
                        {
                            System.out.println("The result is "+s);
                        }
                        public static void main()
                        {
                            sum t1=new sum();
                            sum t2=new sum();
                            sum t3=new sum();
                            t1.input(4,3);
                            t2.input(2,1);
                            t3.add(t1,t2);
                            t3.show();
                        }
                    }
                 The output of the preceding program is as follows:
                   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 herein 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 has been created. And this is done by the method
                 constructor.



                                                                                                                       233
                                                                                              Methods and Constructors  233
   230   231   232   233   234   235   236   237   238   239   240