Created
February 26, 2011 05:58
-
-
Save ketankhairnar/844998 to your computer and use it in GitHub Desktop.
UsingTraits
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
class UsingTraits | |
//refer notes 1,2,3 | |
trait Friend{ | |
val name:String | |
def listen()=println("Your friend "+name+" is listening") | |
} | |
class Human(val name:String) extends Friend | |
class Man(override val name:String) extends Human(name) | |
class Woman(override val name:String) extends Human(name) | |
// refer notes 3 and 4 | |
class Animal | |
class Dog(val name:String) extends Animal with Friend | |
object UsingTraits extends Application{ | |
override def main(args:Array[String]) | |
{ | |
println("======================================================") | |
println(traitNotes) | |
println("======================================================") | |
println("Logic execution strace below") | |
println("======================================================") | |
val ketan = new Human("ketan") | |
ketan.listen | |
val dog = new Dog("pluto") | |
dog.listen | |
} | |
def traitNotes() = | |
{ | |
""" | |
1. A trait is a behavior that can be mixed into or assimilated into class hierarchy. | |
2. A trait is like an interface with partial implementation | |
3. The vals and vars you define and initialize in a trait get internally implemented in the classes that mix the trait in. | |
Any vals and vars defined but not initialized are considered abstract, and the classes that mix in these traits are | |
required to implement them | |
4. When class is not extending any other class; one can mix trait using "extends" keyword; otherwise use "with" keyword. | |
Check above example. 'Dog extends Animal with Friend' | |
5. "Selective mixins" : Not all pets are friendly. So we can mix trait 'Friend' ONLY with the instance of 'friendly' pet. | |
e.g. Lets assume cat with the name 'ruby' is friendly. so add 'Friend' trait for cat instance with | |
name 'ruby' It can be done as => new Cat('ruby') with Friend | |
""" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment