Search code examples
javaconstructorresolveambiguity

Compiler not finding ambiguity among instance variable and parameters passed during constructor initialisation?


package learning;

public class This_keyword {

        int x;
        int y;

        This_keyword(int x,int y){

                x = x;
                y = y;

                System.out.print("Value of 1st :" +x);
                System.out.print("Value of 2nd :" +y);
        }

         public static void main(String args[]){
        This_keyword sample = new This_keyword(4,5);
    } 
}

This should print 0,0 since i didn't used this keyword, but still it is printing 4,5 which are passed as parameterized constructor.

Now have a look at the second code,

     package learning;

     public class This_keyword {

        int x;
        int y;

        This_keyword(int x,int y){

                x = x;
                y = y;
          } 

        void display(){ 
            System.out.print("Value of 1st :" +x);
            System.out.print("Value of 2nd :" +y);
        }


        public static void main(String args[]){

            This_keyword sample = new This_keyword(4,5);
            sample.display();
        } 
}

Now it is prinitng 0,0 which was expected and true since no this keyword was mentioned complier had an ambiguity resolving same name among instance variable and parameters.

Why compiler was able to print the values in first case?? even though there lies an ambiguity over there too!!


Solution

  • In your first example, you are using System.out.print inside of the constructor. Since your constructor accepts an 'x' and a 'y' variable, you end up referring to the 'x' and 'y' values that were passed in, not the fields of your class. If you changed your prints to use 'this.x' and 'this.y' in your first example, then you would get 0 and 0.

    In your second example, your System.out.prints are located in a different method. Notice how your display method does not accept 'x' and 'y' variables locally. Since there is no 'x' or 'y' in the method itself, the program will attempt to use the 'x' and 'y' fields of the class itself, which is why you're getting 0 and 0.

    The keyword 'this' is the pointer (I'm using the word "pointer" casually; not 100% accurate) to the object that made the call. 'this' helps to remove ambiguity when your local variables are the same as your fields or when dealing with inheritance.

    Why not just use a different name for the local variables then? You could, yes. However, when the name for your variables start to become more descriptive, and therefore long, as the complexity of your programs increase, it just makes sense to give certain data certain names without making the names any longer just to distinguish between where it's currently being held.