開発環境
- 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-294-7)の 第9章(継承とポリモーフィズム)11.9(練習問題)練習11-3を解いてみる。
その他参考書籍
練習11-3.
コード
using System;
abstract class Telephone
{
protected string phonetype;
public abstract void Ring();
}
class ElectronicPhone : Telephone
{
public ElectronicPhone()
{
phonetype = "Digital";
}
public override void Ring()
{
Console.WriteLine("Ringing the {0}.", phonetype);
Console.WriteLine("Sound: Pipi, Pipi.");
}
}
class TalkingPhone : Telephone
{
public TalkingPhone()
{
phonetype = "Talking";
}
public override void Ring()
{
Console.WriteLine("Ringing the {0}.", phonetype);
Console.WriteLine("Hello!");
}
}
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. Sound: Pipi, Pipi. Ringing the Talking. Hello! 続行するには何かキーを押してください . . .
ちなみにJavaScriptの場合。
コード(TextWrangler)
var result = "";
var Telephone = function(){
this.phone_type;
};
Telephone.prototype.ring = function(){
throw "サブクラスで定義が必要!";
};
var ElectronicPhone = function(){
this.phone_type = "Digital";
};
ElectronicPhone.prototype = new Telephone();
ElectronicPhone.prototype.ring = function(){
return "Ringing the " + this.phone_type + ".\n" +
"Sound: Pipi, Pipi.";
};
ElectronicPhone.prototype.constructor = ElectronicPhone;
var TalkingPhone = function(){
this.phone_type = "Talking";
};
TalkingPhone.prototype = new Telephone();
TalkingPhone.prototype.ring = function(){
return "Ringing the " + this.phone_type + ".\n" +
"Sound: Hello!";
};
TalkingPhone.prototype.constructor = TalkingPhone;
var ep = new ElectronicPhone();
var tp = new TalkingPhone();
result += ep.ring() + "\n" + tp.ring() + "\n";
$('#pre0').text(result);
pythonの場合。
sample.py
コード(TextWrangler)
#!/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 " + self.phonetype + ".");
print("Sound: Pipi, Pipi.")
class TalkingPhone(Telephone):
def __init__(self):
self.phonetype = "Talking";
def ring(self):
print("Ringing the " + self.phonetype + ".");
print("Sound: Hello!")
ep = ElectronicPhone()
tp = TalkingPhone()
ep.ring()
tp.ring()
入出力結果(Terminal)
$ ./sample.py Ringing the Digital. Sound: Pipi, Pipi. Ringing the Talking. Sound: Hello! $
メモ: JavaScriptとPythonの場合、抽象クラスは無い(?)ので、サブクラスで定義していなかった場合に例外を投げるようにしてみた。
0 コメント:
コメントを投稿