This Keyword in Java

Advertisements

C Tutorial Programming

This keyword refers to the current calling object. This keyword can be used in situation where local variables have same name with class data members or we can say, it can be used in situation where the data member and arguments of member function have same name.

Example of Java This keyword


//Student.java

    class Student
    {
        int Roll;
        String Name;
        double Marks;

        Student(int R,double Mks,String Nm)           //Parameterize Constructor 1
        {
        Roll = R;
        Name = Nm;
        Marks = Mks;
        }

        Student(String Name,double Marks,int Roll)      //Parameterize Constructor 2
        {
            Roll = Roll;
            Name = Name;
            Marks = Marks;
        }

        Student(int Roll,String Name,double Marks)       //Parameterize Constructor 3
        {
            this.Roll = Roll;
            this.Name = Name;
            this.Marks = Marks;
        }

        void Display()
        {
            System.out.print("\n\tRoll : " + Roll);
            System.out.print("\n\tName : " + Name);
            System.out.print("\n\tMarks : " + Marks);
        }

        public static void main(String[] args)
        {

            Student S1 = new Student(1,89.63,"Sumit");
            Student S2 = new Student("Kumar",78.53,2);
            Student S3 = new Student(3,"Gaurav",68.94);

            System.out.print("\n\n\tDetails of Student 1 : ");
            S1.Display();

            System.out.print("\n\n\tDetails of Student 2 : ");
            S2.Display();

            System.out.print("\n\n\tDetails of Student 3 : ");
            S3.Display();

        }
    }

    Output:
                Details of Student 1 :
                Roll : 1
                Name : Sumit
                Marks : 89.63

                Details of Student 2 :
                Roll : 0
                Name : null
                Marks : 0.0

                Details of Student 3 :
                Roll : 3
                Name : Gaurav
                Marks : 68.94

In constructor 1, variables declared in argument list different from variables declared as class data members. When compiler doesn't find Roll, Name, Marks as local variable, then it will find Roll, Name, Marks in class scope and assign values to them. In this case no 'this' keyword is required because both local variables and data members have different names.

But Constructor 2 will not intialize class data members. When we pass values to constructor 2, it will initialize values to itself local variables bcoz variables declared in argument list and variable declared as data members are of same name.

In this situation, we use 'this' keyword to differentiate local variable and class data members as shown in constructor 3.

Advertisement