コンテンツにスキップ

可視性

メソッドはデフォルトでパブリックです。コンパイラは常にそれらを呼び出すことができます。このため、publicキーワードはありません。

メソッドはprivateまたはprotectedとしてマークすることができます。

プライベートメソッド

privateメソッドは、レシーバーなしで、つまりドットの前に何もなしで呼び出すことができます。唯一の例外は、レシーバーとしてのselfです。

class Person
  private def say(message)
    puts message
  end

  def say_hello
    say "hello"      # OK, no receiver
    self.say "hello" # OK, self is a receiver, but it's allowed.

    other = Person.new
    other.say "hello" # Error, other is a receiver
  end
end

privateメソッドはサブクラスから見えることに注意してください。

class Employee < Person
  def say_bye
    say "bye" # OK
  end
end

プライベート型

プライベート型は、定義されている名前空間内でのみ参照でき、完全修飾することはできません。

class Foo
  private class Bar
  end

  Bar      # OK
  Foo::Bar # Error
end

Foo::Bar # Error

privateは、classmodulelibenumalias、および定数と共に使用できます。

class Foo
  private ONE = 1

  ONE # => 1
end

Foo::ONE # Error

プロテクトメソッド

protectedメソッドは、以下の場合にのみ呼び出すことができます。

  1. 現在の型と同じ型のインスタンス
  2. 現在の型と同じ名前空間(クラス、構造体、モジュールなど)内のインスタンス
# Example of 1

class Person
  protected def say(message)
    puts message
  end

  def say_hello
    say "hello"      # OK, implicit self is a Person
    self.say "hello" # OK, self is a Person

    other = Person.new "Other"
    other.say "hello" # OK, other is a Person
  end
end

class Animal
  def make_a_person_talk
    person = Person.new
    person.say "hello" # Error: person is a Person but current type is an Animal
  end
end

one_more = Person.new "One more"
one_more.say "hello" # Error: one_more is a Person but current type is the Program

# Example of 2

module Namespace
  class Foo
    protected def foo
      puts "Hello"
    end
  end

  class Bar
    def bar
      # Works, because Foo and Bar are under Namespace
      Foo.new.foo
    end
  end
end

Namespace::Bar.new.bar

protectedメソッドは、そのクラスまたはその子孫のスコープからのみ呼び出すことができます。これには、protectedメソッドが定義されているのと同じ型のクラススコープとクラスメソッドおよびインスタンスメソッドの本体、およびその型を含むまたは継承するすべての型と、その名前空間内のすべての型が含まれます。

class Parent
  protected def self.protected_method
  end

  Parent.protected_method # OK

  def instance_method
    Parent.protected_method # OK
  end

  def self.class_method
    Parent.protected_method # OK
  end
end

class Child < Parent
  Parent.protected_method # OK

  def instance_method
    Parent.protected_method # OK
  end

  def self.class_method
    Parent.protected_method # OK
  end
end

class Parent::Sub
  Parent.protected_method # OK

  def instance_method
    Parent.protected_method # OK
  end

  def self.class_method
    Parent.protected_method # OK
  end
end

プライベートトップレベルメソッド

privateトップレベルメソッドは、現在のファイルでのみ表示されます。

one.cr
private def greet
  puts "Hello"
end

greet # => "Hello"
two.cr
require "./one"

greet # undefined local variable or method 'greet'

これにより、そのファイルでのみ認識されるヘルパーメソッドをファイルに定義できます。

プライベートトップレベル型

privateトップレベル型は、現在のファイルでのみ表示されます。

one.cr
private class Greeter
  def self.greet
    "Hello"
  end
end

Greeter.greet # => "Hello"
two.cr
require "./one"

Greeter.greet # undefined constant 'Greeter'