Access control

Access control provides controls on who can invoke the method to change the state of the object. Ruby provides three levels of access control.

  1. Private: Private methods are those methods which can only be invoked by the another method of the same class. Private methods are marked separately. The receiver of the private method is self.
  2. Protected: Protected methods can oly be invoked by the methods of the same class or by the methods of the parent class. Protected methods are also marked separately.
  3. Public: Public methods can be called by anyone and has no access control.

Example:

class Person < Animal

    def speak
        puts "Hello!"
    end

    protected 
    
    def eats
        puts "Eating only pretected items"
    end

    private

    def sleep
        puts "Sleeping in private"
    end 

end

In the above example the person class has three methods speak, eats and sleep out of which speak is a public method eats is protected method and sleep is a protected method.

In ruby all the declared variables and constants are private they can only be accessed using getter and setter methods.

Inheritance

Inheritance is an important property of any Object Oriented programming it allows us for code reuse. Ruby supports inheritance using the following syntax:

class Person < Human
    //....
end

In the above example the Person class is inherited from the Human class. Ruby does not support multiple inheritance. We can support multiple inheritance by using mixins. We will discuss about inheritance in ruby in another post.

Leave a Reply

Your email address will not be published. Required fields are marked *