super
@sex = true
end
attr_reader:sex #定义只读属性sex
def call_protected_method
puts get_name_size #调用父类的受保护方法
end
def call_protected_method2(man1)
puts man1.get_name_size #注意这里:这里可以把父类的受保护方法,动态添加到子类实例
end
def call_private_method #子类可以调用父类的私有方法!!! 这一点刚开始很不习惯
test
end
def call_private_method2(man1)
man1.test #注意这里:语法检查虽然可以通过,但是运行时会提示私有方法无法调用,这也是private与protected的区别
end
end
puts "******************************"
aMan = Man.new("jimmy.yang");
aMan.show_name
aMan.call_protected_method
puts aMan.sex
aMan.call_private_method
aMan2 = Man.new("Mike")
aMan.call_protected_method2(aMan2);
#aMan.call_private_method2(aMan2);
a = "abc";
#aMan.call_protected_method2(a); #虽然ruby本身对变量没有类型概念,但是这样却不行,即:在调用父类的受保护方法时,其实是要类型匹配的
puts aMan.class #显示aMan的类名称
运行结果如下:
>ruby classDemo.rb
My name is jimmy
private method(test) in People.
name = jimmy
jimmy
private method(test) in People.
name = 杨俊明
******************************
private method(test) in People.
name = jimmy.yang
10
true
private method(test) in People.
4
Man
>Exit code: 0
作者:菩提树下的杨过
出处:http://yjmyzz.cnblogs.com










