面试题答案
一键面试# 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}"