ruby学習メモ アクセス制御
class TestClass def defaultMethod # public return "default -> public" end protected def protectedMethod # protected return "protected" end private def privateMethod # private return "private" end public def publicMethod # public return "public" end def callOtherProtectedMethod(other) return other.protectedMethod end def callOtherPrivateMethod(other) return other.privateMethod end end
irb(main):472:0* test1 = TestClass.new => #<TestClass:0x297aa20> irb(main):473:0> test1.defaultMethod => "default -> public" irb(main):474:0> test1.protectedMethod NoMethodError: protected method `protectedMethod' called for #<TestClass:0x297aa20> from (irb):474 from ^C:0 irb(main):475:0> test1.privateMethod NoMethodError: private method `privateMethod' called for #<TestClass:0x297aa20> from (irb):475 from ^C:0 irb(main):476:0> test1.publicMethod => "public" irb(main):477:0> irb(main):478:0* test1.callOtherProtectedMethod(test1) => "protected" irb(main):479:0> test1.callOtherPrivateMethod(test1) NoMethodError: private method `privateMethod' called for #<TestClass:0x297aa20> from (irb):450:in `callOtherPrivateMethod' from (irb):479 from ^C:0
上記の callOtherPrivateMethod のように同一クラス、他インスタンスの private メソッドの呼び出しが許可されない。
java の場合は許可される。
java に対して同一クラスでのアクセス許可という点でアクセス制御の方法が若干違う模様