神刀安全网

Mixin Class Composition in Scala

As opposed to languages that only support single inheritance, Scala has a more general notion of class reuse. Scala makes it possible to reuse the new member definitions of a class (i.e. the delta in relationship to the superclass) in the definition of a new class.

Abstract Class

  abstract class AbsInfo {         def isSpecialTrain: Boolean   }  

Trait Object

  trait MyTrain {     def printTrainInfo = {       println("Train Number : 12675")       println("Train Name : KOVAI EXPRESS")     }   }  

Normal Class

  class GeneralQuota {     def printQuotaDetail = println("General Quota")   }

Abstract Class With Interface Method Implementation

  class TatkalQuota extends AbsInfo {     def printQuotaDetail = println("Tatkal Quota")     def isSpecialTrain:Boolean = false   } 

Mixin Class Composition

  class LadiesQuota extends AbsInfo with MyTrain {     def printQuotaDetail = println("Ladies Quota")     def isSpecialTrain:Boolean = false   }

The LadiesQuota class is constructed from a mixin composition of the parents AbsInfo and MyTrain with the keyword with. The first parent is called the abstract class of LadiesQuotaclass, whereas the second (and every other, if present) parent is called a mixin.

Overall Code

object Mixin {   def main(a: Array[String]) = {     val gQuota = new GeneralQuota     gQuota.printQuotaDetail     val tQuota = new TatkalQuota     tQuota.printQuotaDetail     println("Is it Special train : "+tQuota.isSpecialTrain)         val lQuota = new LadiesQuota         lQuota.printQuotaDetail     println("Is it Special train : "+lQuota.isSpecialTrain)     lQuota.printTrainInfo   }     // Abstract Class   abstract class AbsInfo {         def isSpecialTrain: Boolean   }     // Trait Object   trait MyTrain {     def printTrainInfo = {       println("Train Number : 12675")       println("Train Name : KOVAI EXPRESS")     }   }     // Normal Class   class GeneralQuota {     def printQuotaDetail = println("General Quota")   }   // Abstract class with interface method implementation    class TatkalQuota extends AbsInfo {     def printQuotaDetail = println("Tatkal Quota")     def isSpecialTrain:Boolean = false   }     // Mixin Class composition   class LadiesQuota extends AbsInfo with MyTrain {     def printQuotaDetail = println("Ladies Quota")     def isSpecialTrain:Boolean = false   } }

Result:

Mixin Class Composition in Scala

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » Mixin Class Composition in Scala

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址