0

Say I have a simple sample console program like below. My question is in regards to this. Is the sole use of this just so you can use the input variable name to assign to the instance variable? I was wondering what the use of this is other than used in the context of this program?

public class SimpleClass {

    int numberOfStudents;

    public SimpleClass(){
        numberOfStudents = 0;
    }

    public void setStudent(int numberOfStudents){
        this.numberOfStudents = numberOfStudents;
    }

    public void printStudents(){
        System.out.println(numberOfStudents);
    }

    public static void main(String[] args) {

        SimpleClass newRandom = new SimpleClass();
        newRandom.setStudent(5);
        newRandom.printStudents();

    }
}

Previously, when I needed to assign a value to an instance variable name that shares similarities to the input value, I had to get creative with my naming scheme (or lack of). For example, the setStudent() method would look like this:

public void setStudent(int numberOfStudentsI){
    numberOfStudents = numberOfStudentsI;
}

From that example above, it seems like using this replaces having to do that. Is that its intended use, or am I missing something?

theGreenCabbage
  • 5,197
  • 19
  • 79
  • 169

6 Answers6

2

Things are quite the opposite of how you perceive them at the moment: this is such an important and frequently used item in Java/C# that there are many special syntactical rules on where it is allowed to be assumed. These rules result in you actually seeing this written out quite rarely.

However, except for your example, there are many other cases where an explicit this cannot be avoided (Java):

  • referring to the enclosing instance from an inner class;
  • explicitly parameterizing a call to a generic method;
  • passing this as an argument to other methods;
  • returning this from a method (a regular occurrence with the Builder pattern);
  • assigning this to a variable;

... and more.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
1

this is also used if you want to a reference to the object itself:

someMethod(this);

There is no alternative to this syntax (pun intended).

It's also used to call co-constructors, and for C# extension methods.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
1

'this' simply refers to the object itself.

When the compilers looks for the value of 'numberOfStudents', it matches the 'closest' variable with this name. In this case the argument of the function. But if you want to assign it to the class variable, you need to use the 'this.'-notation!

In the method

public void setStudent(int numberOfStudents){
    this.numberOfStudents = numberOfStudents;
}

for example.

'this.numberOfStudents' references the class variable with the name 'numberOfStudents' 'numberOfStudents' references the argument of the method

So, this method simple assigns the value of the parameter to the class variable (with the same name).

Jens
  • 319
  • 3
  • 10
0

in c# you use this to refer the current instance of the class object immagine you have class like this from msdn

    class Employee
    {
        private string name;
        private string alias;
        private decimal salary = 3000.00m;

        // Constructor: 
        public Employee(string name, string alias)
        {
            // Use this to qualify the fields, name and alias: 
            this.name = name;
            this.alias = alias;
        }
        // Printing method: 
        public void printEmployee()
        {
            Console.WriteLine("Name: {0}\nAlias: {1}", name, alias);
            // Passing the object to the CalcTax method by using this:
            Console.WriteLine("Taxes: {0:C}", Tax.CalcTax(this));
        }

        public decimal Salary
        {
            get { return salary; }
        }
    }

    class Tax
    {
        public static decimal CalcTax(Employee E)
        {
            return 0.08m * E.Salary;
        }
    }

    class MainClass
    {
        static void Main()
        {
            // Create objects:
            Employee E1 = new Employee("Mingda Pan", "mpan");

            // Display results:
            E1.printEmployee();
        }
    }
    /*
    Output:
        Name: Mingda Pan
        Alias: mpan
        Taxes: $240.00
     */
BRAHIM Kamel
  • 13,492
  • 1
  • 36
  • 47
0

You have different scopes of variables in Java/C#. Take this example below. Although this.numberOfStudents and numberOfStudents have the same name they are not identical.

public void setStudent(int numberOfStudents){
    this.numberOfStudents = numberOfStudents;
}

this.numberOfStudents is a variable called numberOfStudents that is in the instance of this class. this always points on the current instance.

public void setStudent(int numberOfStudents) that numberOfStudents is a new variable that is just available in this method.

Lukas Eichler
  • 5,689
  • 1
  • 24
  • 43
0

keyword "this" refers to an object of the current class (SimpleClass) on the fly.

public class SimpleClass(){

    private int a;
    private int b;
    private int c;

    public SimpleClass(int a, int b){
       this.a = a;
       this.b = b;
    }

    public SimpleClass(int a, int b, int c){
       // this constrcutor
       this(a,b);
       this.c = c;
    }
}
openmike
  • 272
  • 1
  • 9