ruby的类-继承方法定义类变量与实例变量

感性的认识了一下ruby的类

class Song
  #类变量
  @@plays = 0
  #构造函数
  def initialize(name,artist,duration)
    #实例变量
    @name = name
    @artist = artist
    @duration = duration
  end
  def to_s
    "Song: #@name--#@artist (#@duration) plays:#@@plays"
  end
end
#类继承
class KaraokeSong < Song
  #类方法
  def self.getType
    "KaraokeSongType"
  end
  
  def initialize(name,artist,duration,lyrics)
    super(name,artist,duration)
    @lyrics = lyrics      
  end
  
  #重写
  def to_s
    super + " duration:#@duration"
  end
  #protected方法
  protected
  def nono
    
  end
  #private方法
  private
  def noop
    "noop"
  end
end
  
song = KaraokeSong.new("My Way", "Sinatra", 100 , "The Way....")
puts(song.to_s)
puts(KaraokeSong.getType)

你可能感兴趣的:(Ruby,Sinatra)