削除された内容 追加された内容
Ef3 (トーク | 投稿記録)
→‎包含と継承: JavaScript/クラス#包含と継承を、Rubyに移植したRuby#包含と継承を、Crystalに移植しました。
タグ: 2017年版ソースエディター
Ef3 (トーク | 投稿記録)
→‎包含と継承: 「Crystalらしいコード」に変更
タグ: 2017年版ソースエディター
403 行
;包含と継承:<syntaxhighlight lang=crystal line>
class Point
def initialize(@x = 0, @y = 0)
p("Point::constructorinitialize")
@x = x
@y = y
end
def move(dx = 0, dy = 0)
@x, @y += @x + dx, @y + dy
@y += dy
p("Point::move")
self
419 ⟶ 416行目:
def initialize(x = 0, y = 0)
@location = Point.new(x, y)
p("Shape::constructorinitialize")
end
def move(x, y)
429 ⟶ 426行目:
 
class Rectangle < Shape
def initialize(x = 0, y = 0, @width = 0, @height = 0)
super(x, y)
p("Rectangle::constructorinitialize")
@width = width
@height = height
p("Rectangle::constructor")
end
end
439 ⟶ 434行目:
p("Create a Rectangle!")
rct = Rectangle.new(12, 32, 100, 50)
p("rct = ",! rct)
p("! rct.is_a?( Rectangle ) => ",
p! rct.is_a?(Rectangle) Shape )
p("! rct.is_a?( ShapePoint ) => ", rct.is_a?(Shape))
p("rct.is_a?( Point ) => ", rct.is_a?(Point))
rct.move(11, 21)
p("rct = ",! rct)
rct2 = Rectangle.new(1, 2, 10, 150)
p("! rct = ", rct)rct2
p("rct2 = ", rct2)
</syntaxhighlight>
;実行結果:<syntaxhighlight lang=text>
"Create a Rectangle!"
"Point::constructorinitialize"
"Shape::constructorinitialize"
"Rectangle::constructorinitialize"
rct # => #<Rectangle:0x80096de400x80096ee40 @location=#<Point:0x80096ee600x80096fe60 @x=12, @y=32>, @width=100, @height=50>
"rct = "
"rct.is_a?(Rectangle) Shape )# => "true
#<Rectangle:0x80096de40 @location=#<Point:0x80096ee60 @x=12, @y=32>, @width=100, @height=50>
"rct.is_a?(Shape) Rectangle )# => "true
p("rct.is_a?( Point ) # => ", rct.is_a?(Point))false
true
"rct.is_a?( Shape ) => "
true
"rct.is_a?( Point ) => "
false
"Point::move"
"Shape::move"
rct # => #<Rectangle:0x80096de400x80096ee40 @location=#<Point:0x80096ee600x80096fe60 @x=23, @y=53>, @width=100, @height=50>
"rct = "
"Point::constructorinitialize"
#<Rectangle:0x80096de40 @location=#<Point:0x80096ee60 @x=23, @y=53>, @width=100, @height=50>
"Shape::constructorinitialize"
"Point::constructor"
"Rectangle::constructorinitialize"
"Shape::constructor"
rct # => #<Rectangle:0x80096de400x80096ee40 @location=#<Point:0x80096ee600x80096fe60 @x=23, @y=53>, @width=100, @height=50>
"Rectangle::constructor"
rct2 # => #<Rectangle:0x80096de200x80096ee20 @location=#<Point:0x80096ee500x80096fe50 @x=1, @y=2>, @width=10, @height=150>
"rct = "
#<Rectangle:0x80096de40 @location=#<Point:0x80096ee60 @x=23, @y=53>, @width=100, @height=50>
"rct2 = "
#<Rectangle:0x80096de20 @location=#<Point:0x80096ee50 @x=1, @y=2>, @width=10, @height=150>
</syntaxhighlight>