class Main
def say_hello
puts "Hello"
end
private
def say_hi
puts "hi"
end
end
class SubMain < Main
def say_hello
puts "Testing #{say_hi}"
end
end
test = SubMain.new
test.say_hello()
OUTPUT:
hi
Testing
Since method overriding works on dynamic binding, it's not possible to override the private method in Java. private methods are not even visible to the Child class, they are only visible and accessible in the class on which they are declared.
Private methods are inherited in sub class ,which means private methods are available in child class but they are not accessible from child class,because here we have to remember the concept of availability and accessibility.
The private methods in Ruby can also be inherited just like public and protected methods.
The difference is that in ruby you can call private methods in subclasses implicitly but not explicitly. Protected can be called both ways. As for why? I guess you would have to ask Matz.
Example:
class TestMain
protected
def say_hola
puts "hola"
end
def say_ni_hao
puts "ni hao"
end
private
def say_hi
puts "hi"
end
def say_bonjour
puts "bonjour"
end
end
class SubMain < TestMain
def say_hellos
# works - protected/implicit
say_hola
# works - protected/explicit
self.say_ni_hao
# works - private/implicit
say_hi
# fails - private/explicit
self.say_bonjour
end
end
test = SubMain.new
test.say_hellos()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With