Ruby类的继承

Ruby继承的语法安全

class DerivedClass < BaseClass
    #some stuff
end

 < 为继承符号ide

重写(override) 的概念函数

有时, 咱们但愿子类从父类继承来的方法能够作与父类不相同的事情,这就须要在子类中重写方法。例如, 你有一个类名字叫Email继承于类Message,两个类都有send方法,可是Email类的send方法须要有邮件地址和一系列邮件协议,可是Message中的send方法并不知道这些,与其在Email类中添加send_mail方法,而从父类继承的send方法弃之不用, 不如显式的修改send方法以适应Email的需求。spa

例如:code

class Creature
  def initialize(name)
    @name = name
  end
  
  def fight
    return "Punch to the chops!"
  end
end

# Add your code below!
class Dragon < Creature
    def fight
        return "Breathes fire!"
    end
end
    
dragon = Dragon.new("dragon")
dragon.fight
--------------------------------------------------
输出:
"Breathes fire!"

 

另外一方面, 有时子类发现它所须要的继承自父类的方法已经被改写, 不要惊慌, 咱们能够直接获取父类的响应方法, 这须要使用super关键字。blog

语法为:继承

class DerivedClass < Base
  def some_method
    super(optional args)
      # Some stuff
    end
  end
end

当你在方法中调用super, 这就是告诉Ruby,在父类中找到与调用super的这个方法同名的函数,若是找到, 那么Ruby将会使用其父类版本的这个方法。接口

例如:it

class Creature
  def initialize(name)
    @name = name
  end
  
  def fight
    return "Punch to the chops!"
  end
end

# Add your code below!
class Dragon < Creature
    def fight
        puts "Instead of breathing fire..."
        super
    end
end
    
dragon = Dragon.new("w")
dragon.fight
-------------------------------------------------------------------
输出:
Instead of breathing fire...
"Punch to the chops!"

 

Ruby不支持多继承。然而Ruby容许使用mixin, 这个咱们稍后再讲。io

 

为了程序的安全性, Ruby容许咱们显式地对方法进行public或private声明, public方法容许做为接口被调用,private方法则对外界不可见。若是不写public或private,Ruby默认为public。

 1 class Person
 2   def initialize(name, age)
 3     @name = name
 4     @age = age
 5   end
 6   
 7   public    # This method can be called from outside the class.
 8   
 9   def about_me
10     puts "I'm #{@name} and I'm #{@age} years old!"
11   end
12   
13   private   # This method can't!
14   
15   def bank_account_number
16     @account_number = 12345
17     puts "My bank account number is #{@account_number}."
18   end
19 end
20 
21 eric = Person.new("Eric", 26)
22 eric.about_me
23 eric.bank_account_number  #错误, 调用了私有方法!
 -------------------------------------------------------------------------
 输出:
 I'm Eric and I'm 26 years old!
 private method `bank_account_number' called for #<Context::Person:0x0000000262d930 @name="Eric", @age=26>

 

用attr_reader, attr_writer读写属性(attribute)

根据前面咱们所学,若是想要访问定义在类中的属性,例如,咱们想要访问@name实例变量, 咱们必须这么写

def name
  @name
end

若是咱们想要咱们想修改@name实例变量,那么咱们要这么写:

def name=(value)
  @name = value
end

如今没必要这么麻烦了。咱们能够用attr_reader和attr_writer来读写变量,以下:

class Person
  attr_reader :name
  attr_writer :name
  def initialize(name)
    @name = name
  end
end

当遇到上面的代码时,Ruby自动地作相似以下的事情:

def name
  @name
end

def name=(value)
  @name = value
end

像变魔术同样, 咱们能够随意读写变量了!咱们仅仅是把变量(转换为symbol)传给attr_reader和attr_writer

若是你既想read也想write一个变量, 那么还有比使用attr_reader和attr_writer更加简短的办法, 那就是用attr_accessor.

相关文章
相关标签/搜索