为什么puts不打印在超类中初始化的名称和id实例变量?

时间:2016-01-26 14:21:23

标签: ruby

# super class
class Wages 
  attr_accessor :name ,:id

  def initialize(name="first",id=0.0)
    self.name=name
    self.id=id
  end
end

class HourEmployee<Wages
  attr_accessor :hours ,:payperhour

  def initialize
    puts "please enter the no of hours and payperhour"
    hours=0.0
    payperhour=0.0
  end

  def pay_per_hour
    puts "the employee name #{self.name}" 
    puts "employee id is #{@id}"
    puts "employee Wages for his work are "
    self.calculate
  end

  def calculate
    puts "please enter the no of hours"
    @Wages = hours*payperhour
    puts "#{@Wages}"
  end
end

a=HourEmployee.new
a.hours=40
a.payperhour=10
a.pay_per_hour

为什么代码不打印它应该打印的名称和id 我已经在超类中初始化了类工资,但是当我打印名称时,它为名称和id提供了空白

2 个答案:

答案 0 :(得分:0)

您需要从派生类调用父类的构造函数。使用super来执行此操作。

答案 1 :(得分:0)

您必须为superClass

调用构造函数
class HourEmployee < Wages
  ...

  def initialize
    super
    puts "please enter the no of hours and payperhour"
    hours=0.0
    payperhour=0.0
  end
  ...
end

例如

class A
  def initialize
    puts "Class A constructor"
  end
end

class B < A
  def initialize
    puts "Class B constructor"
  end
end

class C < A
  def initialize
    super
    puts "Class C constructor"
  end
end

a = A.new
# Class A constructor
b = B.new
# Class B constructor
c = C.new
# Class A constructor
# Class C constructor