開発環境
- Microsoft Windows 8 Pro 64bit 日本語 (OS)
- Microsoft Visual Studio Express 2012 for Windows Desktop (IDE)
- プログラミング言語: C#
『初めてのC# 第2版』(Jesse Liberty+Brian MacDonald著、日向俊二訳、オライリー・ジャパン、2006年、ISBN978-487311-394-7)の 第11章(継承とポリモーフィズム)11.9(練習問題)練習11-3を解いてみる。
その他参考書籍
練習11-3.
コード
using System; abstract class Telephone { protected string phonetype; public abstract void Ring(); } class ElectronicPhone : Telephone { public ElectronicPhone() { this.phonetype = "Digital"; } public override void Ring() { Console.WriteLine("Ringing the {0}. Pipi, Pipi.", phonetype); } } class TalkingPhone : Telephone { public TalkingPhone() { this.phonetype = "Talking"; } public override void Ring() { Console.WriteLine("Ringing the {0}. Talking!", phonetype); } } class Tester { public void Run() { ElectronicPhone ep = new ElectronicPhone(); TalkingPhone tp = new TalkingPhone(); ep.Ring(); tp.Ring(); } static void Main() { Tester t = new Tester(); t.Run(); } }
入出力結果(Console Window)
Ringing the Digital. Pipi, Pipi. Ringing the Talking. Talking! 続行するには何かキーを押してください . . .
ちなみにJavaScriptの場合。
コード(BBEdit)
function Telephone(){ this.phonetype; // JavaScriptには抽象クラスはないので例外を投げるようにする、 this.ring = function(){ throw "抽象メソッド"; }; } function ElectronicPhone(){ this.phonetype = "Digital"; Telephone.apply(this, arguments); this.ring = function(){ $('#pre0').append("Ringing the " + this.phonetype + ". Pipi, Pipi.\n"); }; } ElectronicPhone.prototype = new Telephone(); function TalkingPhone(){ this.phonetype = "Talking"; Telephone.apply(this, arguments); this.ring = function(){ $('#pre0').append("Talking the " + this.phonetype + ". Talking!\n"); }; } TalkingPhone.prototype = new Telephone(); var ep = new ElectronicPhone(); var tp = new TalkingPhone(); ep.ring(); tp.ring();
pythonの場合。
sample.py
コード(BBEdit)
#!/usr/bin/env python3.3 # -*- coding: utf-8 -*- class Telephone: def __init__(self): self.phonetype = "Telephone" def ring(self): # 抽象クラスはないので、サブクラスで未定義の場合に例外を発生させる raise Exception("抽象メソッド") class ElectronicPhone(Telephone): def __init__(self): self.phonetype = "Digital" def ring(self): print("Ringing the {0}. Pipi, Pipi.".format(self.phonetype)) class TalkingPhone(Telephone): def __init__(self): self.phonetype = "Talking" def ring(self): print("Talking the {0}. Talking!".format(self.phonetype)) if __name__ == '__main__': ep = ElectronicPhone() tp = TalkingPhone() ep.ring() tp.ring()
入出力結果(Terminal)
$ ./sample.py Ringing the Digital. Pipi, Pipi. Talking the Talking. Talking! $
0 コメント:
コメントを投稿