MST

星途 面试题库

面试题:Ruby代码整洁之道之高级难度:类的继承与多态优化

设计一个Ruby程序,有一个基类 `Shape`,包含 `area` 抽象方法。然后有两个子类 `Circle` 和 `Rectangle` 继承自 `Shape`,分别实现 `area` 方法计算圆的面积和矩形的面积。在代码实现过程中,依据《Ruby代码整洁之道》,优化代码结构,确保继承关系清晰,方法实现易于理解和维护,例如合理使用访问修饰符等。
34.3万 热度难度
编程语言Ruby

知识考点

AI 面试

面试题答案

一键面试
# Shape基类,定义抽象方法area
class Shape
  # 定义抽象方法area,要求子类必须实现
  def area
    raise NotImplementedError, "子类必须实现area方法"
  end
  private_class_method :new
end

# Circle子类,继承自Shape,实现圆的面积计算
class Circle < Shape
  def initialize(radius)
    @radius = radius
  end

  def area
    Math::PI * @radius**2
  end
end

# Rectangle子类,继承自Shape,实现矩形的面积计算
class Rectangle < Shape
  def initialize(length, width)
    @length = length
    @width = width
  end

  def area
    @length * @width
  end
end

使用示例:

circle = Circle.new(5)
puts "圆的面积: #{circle.area}"

rectangle = Rectangle.new(4, 6)
puts "矩形的面积: #{rectangle.area}"