Absract Classes
A great use for abstract classes are where you want to have a class but don't want to create objects based on the class. By defining an abstract class we can create a blueprint for subclasses.
Following example demonstrates inheriting from an abstract class but having different constructors:
abstract class Shape
end
# Circle inherits from Shape
class Circle < Shape
def initialize(@radius : Float64)
end
end
class Rectangle < Shape
def initialize(@width : Float64, @height : Float64)
end
end
crc = Circle.new(4)
rec = Rectangle.new(2, 4)
The following example is a more common pattern where we define an abstract method on the abstract class, thus making sure that the classes which implement from the abstract, implement the abstract methods. If they don't, you'll get a compilation error:
abstract class Shape
abstract def area : Number
end
# Circle inherits from Shape
class Circle < Shape
def initialize(@radius : Float64)
end
def area : Number
MATH::PI * radius * 2
end
end
crc = Circle.new(12)
p crc.area # => 323......
# The following class won't compile because it doesn't implement
# area method:
class Rectangle < Shape
def initialize(@width : Float64, @height : Float64)
end
end