2009年8月24日月曜日

Rで仮想クラス (virtual class) の定義をする

Rでは、仮想クラス (virtual class) というものがあります。
他の言語でいうところの抽象クラス (abstract class) に相当するものです。
仮想クラスは、抽象クラス同様、インスタンスを生成できないようになっています。

以下、PHPの抽象クラスとRの仮想クラスです。
まず、PHPから。
<?php
abstract class Animal {
public $color;

public function eat() {
print("むしゃむしゃ");
}

protected abstract function cry();
}

class Dog extends Animal {
public function cry() {
print("ワンワン");
}
}

//doubutsu = new Animal();
// //Fatal error: Cannot instance abstract class Animal

wanchan = new Dog();
wanchan->eat();
wanchan->cry();
?>


次は、Rです。
setClass("Animal", 
representation=representation(color="character", "VIRTUAL"))
setGeneric("eat", function(this) standardGeneric("eat"))
setGeneric("cry", function(this) standardGeneric("cry"))
setMethod("eat", "Animal",
function(this) {
print("むしゃむしゃ")
})
setClass("Dog", contain="Animal")
setMethod("cry", "Dog",
function(this) {
print("ワンワン")
})

#doubutsu <- new("Animal")
# #Error in new("Animal") :
# # trying to generate an object from a virtual class ("Animal")

wanchan <- new("Dog")
eat(wanchan)
cry(wanchan)