c-MOS NOT ゲート

第8回放送授業
「ソフトウェアのしくみ」
8 オブジェクト指向
プログラム言語(2)
8.3 オブジェクト指向
プログラム言語の実際
• クラス 円図形
• インスタンス 円A、円B、…
• 属性(インスタンス変数) 位置、
半径、色、縁の色、…
• メソッド 現れる、消える、移動する、
半径を変える、色を変える…
• 属性(インスタンス変数)
– Figure
@x, @y
– Circle
@x, @y, @r
• メソッド
– Figure
initialize(x, y)
pos
– Circle
initialize(x, y, r)
radius
draw
erase
# 図形のスーパクラス(位置だけ保有)
class Figure
def initialize(x=0.0, y=0.0)
@xorg = x
@yorg = y
end
# 位置を知るメソッド
def pos
[@xorg, @yorg]
end
end
# 円のクラス(中心位置と半径+描画+消去)
class Circle < Figure
def initialize(x=0.0, y=0.0, r=0.0)
super(x, y)
@r = r
end
def radius
@r
end
#(続く)
#(続き)
def draw
# 本来,OSの図形を描くサブプログラムを呼び出し
# putsの出力文は継続行
puts("draw circle:
org=[#{@xorg},#{@yorg}],radius=#{@r}")
end
#(続く)
#(続き)
def erase
# 本来,OSの図形を消すサブプログラムを呼び出し
# putsの出力文は継続行
puts("erase circle:
org=[#{@xorg},#{@yorg}],radius=#{@r}")
end
end
# 円 c1 の生成
c1 = Circle.new(1.5, 0.5, 1.0)
c1.draw # 円 c1 の描画
# 円 c2 の生成
c2 = Circle.new(3.5, 1.5, 0.5)
c2.draw # 円 c2 の描画
c2.@r
# これは許されていない
# c2.pos で何が表示されるか
puts("position of circle: ", c2.pos)
c1.erase # 円 c1 の消去
c2.erase # 円 c2 の消去
• 継承
• 多様性
• カプセル化
オブジェクト指向
プログラムを作ってみよう
• 親子のような家系が作られる
• 点→円→楕円
↓
正方形→長方形→平行四辺形→多角形
応用 Square
• Figure を継承
• 一辺の長さを返すメソッド side を追加
しよう
# 円のクラス(中心位置と半径+描画+消去)
class Circle < Figure
def initialize(x=0.0, y=0.0, r=0.0)
super(x, y)
@r = r
end
def radius
@r
end
#(続く)
#(続き)
def draw
# 本来,OSの図形を描くサブプログラムを呼び出し
# putsの出力文は継続行
puts("draw circle:
org=[#{@xorg},#{@yorg}],radius=#{@r}")
end
#(続く)
#(続き)
def erase
# 本来,OSの図形を消すサブプログラムを呼び出し
# putsの出力文は継続行
puts("erase circle:
org=[#{@xorg},#{@yorg}],radius=#{@r}")
end
end
# 円 c1 の生成
c1 = Circle.new(1.5, 0.5, 1.0)
c1.draw # 円 c1 の描画
# 円 c2 の生成
c2 = Circle.new(3.5, 1.5, 0.5)
c2.draw # 円 c2 の描画
c2.@r
# これは許されていない
# c2.pos で何が表示されるか
puts("position of circle: ", c2.pos)
c1.erase # 円 c1 の消去
c2.erase # 円 c2 の消去
8.4 オブジェクト指向
プログラム言語のまとめ
• クラスの定義
– メソッド
• コンストラクタ initialize
• デストラクタ
– 属性 / インスタンス変数
• よく使われるクラスはパッケージとして
事前に用意されていることが多い
• スーパクラス、サブクラス
– 継承
– 多様性
– カプセル化
• カプセル化
– アクセス制限
– アクセス修飾子:
• public
• private
• protected
• インスタンスの生成: new
• 「インスタンス.メソッド」