Chinaunix首页 | 论坛 | 博客
  • 博客访问: 62328
  • 博文数量: 33
  • 博客积分: 841
  • 博客等级: 准尉
  • 技术积分: 340
  • 用 户 组: 普通用户
  • 注册时间: 2010-03-20 20:54
文章分类

全部博文(33)

文章存档

2011年(33)

分类: Python/Ruby

2011-02-19 11:14:40

  1. class Test
  2.     def method1 #默认为公有方法
  3.     puts "This is a public method"
  4.     end

  5.     protected         #保护方法
  6.     def method2
  7.     puts "This is a protected method"
  8.     end
  9.     
  10.     private         #私有方法
  11.     def method3
  12.     puts "This is a private method"
  13.     end

  14.     public    
  15.     def test_protected(arg) #arg是Test类的对象
  16.         arg.method2     #正确,可以访问同类其他对象的保护方法
  17.     end

  18.     def test_private(arg)    #arg是Test类的对象
  19.         #arg.method3 #错误,不能访问同类其他对象的私有方法
  20.     puts "don't call obj's private method"
  21.     end
  22. end

  23. obj1 = Test.new
  24. obj2 = Test.new
  25.         
  26. obj1.test_protected(obj2)
  27. obj1.test_private(obj2)

在C++中有对象不能访问类的私有方法,因此有了友元。

RubyC++/Java的一个显著不同是存取控制是程序运行时决定的而不是静态绑定的。所以只有在访问一个受限制的方法时才会产生运行时错误。

阅读(627) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~