Created
October 8, 2008 14:47
-
-
Save takedasoft/15532 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* ExtendCookBook.scala | |
* 継承アレコレ | |
*/ | |
package jp.takeda_soft.examples | |
/**「何か」、生き物か、食べ物か */ | |
trait Some{ | |
def isCreature:boolean | |
def isFood:boolean | |
} | |
/** 直方体 */ | |
abstract class Rectangular{ | |
type T //中身の型を「仮決め」しておく。 | |
/**中身*/ | |
var contents:T = _ //なんだかわからないけど何か実装しておく、のアンダーバー | |
/** 格納できるか */ | |
def hasCavity:boolean | |
} | |
/** この直方体は、「何か」の入れ物 */ | |
class Box extends Rectangular{ | |
type T = Some //中身の「型」を決める | |
override def hasCavity = true | |
def put(some:T):Unit = { this.contents = some } | |
def get:T = this.contents | |
def maybe:String = contents match{ | |
case null => "I don't know" | |
case _ => | |
(if( contents.isCreature && contents.isFood ) "Refrigerator" | |
else{ | |
contents + "'s " + | |
( if( contents.isCreature ) "house" else "case" ) | |
}) | |
} | |
} | |
/** 動物。種類と泣き声で。 */ | |
abstract class Animal(val kind:String)(val bark:String) extends Some{ | |
def isCreature:boolean = true | |
} | |
/** 犬。名前をいれて生成する */ | |
class Dog(val name:String) extends Animal("Dog")("Bow"){ | |
def isFood = false | |
} | |
object ExtendCookBook { | |
def main(args:Array[String]){ | |
var box = new Box //何かを入れる箱 | |
///////// パターン1 ///////////// | |
object pochi extends Dog("Pochi"){ | |
override def toString:String = bark + "! "+ name | |
} | |
box.put(pochi) //箱にポチを入れる。 | |
println( box.maybe ) //たぶんコノ箱は・・・ | |
///////// パターン2 ///////////// | |
val choco = new Some{ //無名クラス | |
def isFood = true | |
def isCreature = false | |
override def toString = "chocolate" | |
} | |
box.put(choco) | |
println( box.maybe )//たぶんコノ箱は・・・ | |
///////// パターン3 ///////////// | |
object beef extends Animal("Cow")("Mooh"){ | |
def isFood = true | |
} | |
box.put(beef) | |
println( box.maybe )//たぶんコノ箱は・・・ | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment