Search code examples
oopmethodsthisprivateprivate-methods

Why use this when accessing a private method?


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)
    }

Solution

  • 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.