0

I have a question regarding oop. It might seem really trivial. I have seen example online where they use this to access a private method. Is it really necessary? Is it language specific?

Here is an example which can be done with or withour this.

class A {
    def test(): String = {
        val x = this.test_2()
        x
    }

    private def test_2(): String = {
        "This is working"
    }
}

object Main extends App {
        val a = new A
        val x = a.test
        println(x)
    }

Here the same code without this. both are working.

class A {
    def test(): String = {
        val x = test_2()
        x
    }

    private def test_2(): String = {
        "This is working"
    }
}

object Main extends App {
        val a = new A
        val x = a.test
        println(x)
    }
odbhut.shei.chhele
  • 5,834
  • 16
  • 69
  • 109

2 Answers2

2

Some languages won't accept the use of a method without the this, like python (self.), but in most case, it's a matter of readability and safety.

If you define a function out of the class with the same name as a method of the class, it can cause a problem.

By adding this, you know it's a method from the class.

Morb
  • 534
  • 3
  • 14
1

The "this" keyword refers to the class which you are currently writing code in it. It is mainly use to distinct between method parameters and class fields.

For example, let's assume you have the following class:

public class Student
{
string name = ""; //Field "name" in class Student

//Constructor of the Student class, takes the name of the Student
//as argument
public Student(string name)
{
   //Assign the value of the constructor argument "name" to the field "name"
   this.name = name; 
   //If you'd miss out the "this" here (name = name;) you would just assign the
   //constructor argument to itself and the field "name" of the
   //Person class would keep its value "".
}
}
Naved Ansari
  • 650
  • 2
  • 13
  • 31