package lyzx.com.basic.day02
abstract class Fly {
def howFly():String
def howlongTofly():Int
}
package lyzx.com.basic.day02
/**
* 伴生对象也可以继承抽象类来扩展功能
*/
class SuperMan {
var code = 0
var name = ""
def this(_code:Int,_name:String){
this()
this.code = _code
this.name = _name
}
override def toString = s"SuperMan($code, $name)"
}
/**
* 通过实现apply方法以简化构造伴生对象
*/
object SuperMan extends Fly {
override def howFly(): String = "超人横着飞!"
override def howlongTofly(): Int = 120
def apply(_code: Int, _name: String): SuperMan = new SuperMan(_code, _name)
}
使用object实现类似于java枚举
package lyzx.com.basic.day02
class Season {
}
/**
* 用object模拟枚举类
*/
object Season extends Enumeration {
val SPRING = Value(0,"spring")
val SUMMER = Value(10,"summer")
val AUTUMN = Value(20,"autumn")
val WINTER = Value(30,"winter")
}
测试类
package lyzx.com.basic.day02
class T4 {
def f1(): Unit ={
val p = new Person
println(p.getMyCountry())
println(p.getMyHeadNum())
println(p.getMyLegNum())
}
def f2(): Unit ={
println(SuperMan.howFly()+" 他可以飞翔 "+SuperMan.howlongTofly()+"分钟")
}
/**
* object中非常重要的一个特殊方法,就是apply方法
* 通常在伴生对象中实现apply方法,并在其中实现构造伴生类的对象的功能
* 而创建伴生类的对象时,通常不会使用new Class的方式,而是使用Class()的方式,
* 隐式地调用伴生对象得apply方法,这样会让对象创建更加简洁
*
* 很明显第一个构造SuperMan比第二个简洁
* 而且可以在apply方法中做类似于AOP代理之类的事
*/
def f3(): Unit ={
val s1 = SuperMan(1,"lyzx")
// val s1 = new SuperMan(1,"lyzx")
println(s1.toString)
}
def f4(): Unit ={
// val s1 = Season.SPRING;
//可以通过名字获取Season的值
val spring = Season.withName("spring")
//通过代码获取枚举值,注意不是下标值
val summer = Season(20)
println(spring +" "+summer)
val spring2 = Season(0)
println(spring2 == spring)
//遍历枚举类
for(e <- Season.values)
println(e)
}
}
object T4{
def main(args: Array[String]): Unit = {
val t = new T4
t.f4()
}
}