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