0
Posted on Friday, August 25, 2017 by 醉·醉·鱼 and labeled under
Ruby中的继承不仅仅可以继承实例方法,还可以继承类方法。但是,对于MIXIN的类方法,只能够用BASE.EXTEND来实现了。


class Person
  def self.method_1
    puts "I'm Person class method 1"
  end

  class << self
    def method_2
      puts "I'm Person class method 2"
    end
  end

  def method_3
    puts "I'm instance method 3"
  end


  protected

  def protected_method_1
    puts "I'm protected_method_1"
  end

  private

  def private_method_1
    puts "I'm private_method_1"
  end


end

class Phoenix < Person
  
  def method_4
    puts "I'm instance method 4"
  end

  def call_protected_method_1
    puts "going to call protected_method_1 from Phoenix"
    protected_method_1
  end

  def call_private_method_1
    puts "going to call private_method_1 from Phoenix"
    private_method_1
  end
end

Phoenix.method_1 #ok to inherit class methods
Phoenix.method_2 #ok to inherit class methods

phoenix = Phoenix.new

phoenix.method_3 #ok to inherit instance methods
phoenix.method_4 #ok

phoenix.call_protected_method_1 #ok to call protected method in parent class
# phoenix.protected_method_1 # failed. you could not call it directly
phoenix.call_private_method_1 #ok to call private method in parent class
# phoenix.private_method_1 #failed

# However, mixin class methods could not be inherited unless call base.extend
0
Responses to ... Inherit in Ruby

Post a Comment