Comparing 3 Methods Public, Protected, Private In Rails

Tram Ho

Overview Of Public, Private, Protected

First, when it comes to encapsulation (encapsulation) in languages ​​we imagine these methods. The public, protected and private methods are specific to OOP encapsulation, which refers to the accessibility of the methods. By default, all methods are public. If no method access is specified, it will be public. The protected and private methods cannot be accessed freely, and so when an instance of the object is available, you won’t be able to call those methods.

1. Public

  • With the public method, we can call that method outside the class, use in that class and in inheritance, the subclass can call the public method from the parent class and use it.
  • By default, methods that are not declared in the public are public so we will have two ways to declare the public method.

  • I will take the example of the public method to make it easier for you to understand
  • VD1:

  • Result:
  • VD2:

  • Result:

2. Protected

  • With the protected method, we cannot call that method outside the class and only call it inside the class and its subclasses.
  • The question is: If so, how can we get data from the protected method while not calling it externally?
  • According to his research, the protected it can call get data as follows:
    • Use the public method to call the protected method to get data
    • VD1

    • Result:

    • VD2

    • Result:

3.Private

  • Similar to the protected method, we cannot call that method outside the class and only call it inside the class and its subclasses.
  • Along with the question at protected is: If so, how can we get data from such protected method while not calling it externally?
  • It is different from protected as it cannot be used by self.name_method
  • The example shows the difference between private and protected, for self to use self it still works fine and private it will not fail.

  • Result:
  • For example, to get data from a normal private + method
    • Result:

generality

For a programmer, I think the methods of the method are indispensable. I hope through this article you can understand more about those methods. Thank you for reading

Happy coding 🌻

Share the news now

Source : Viblo