Access control provides controls on who can invoke the method to change the state of the object. Ruby provides three levels of access control.
- 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.
- 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.
- Public: Public methods can be called by anyone and has no access control.
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
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 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.