Created
July 15, 2014 18:57
-
-
Save rbishop/40138b6082ba26c681fc to your computer and use it in GitHub Desktop.
Inheritance and private vs protected
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Parent | |
def initialize(name) | |
@name = name | |
end | |
private | |
attr_accessor :name | |
end | |
class Child < Parent | |
def parents_name(parent) | |
parent.name | |
end | |
end | |
bob = Parent.new("Bob") | |
betty = Child.new | |
betty.parents_name(bob) | |
#=> NoMethodError: private method `name' called for #<Parent:0x007fbf240a2770 @name="Bob> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Parent | |
def initialize(name) | |
@name = name | |
end | |
protected | |
attr_accessor :name | |
end | |
class Child < Parent | |
def parents_name(parent) | |
parent.name | |
end | |
end | |
bob = Parent.new("Bob") | |
betty = Child.new | |
betty.parents_name(bob) | |
#=> "Bob" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I see. This has nothing to do with inheritance, you can demonstrate the same problem without a child class.