//定义trait
//1.不是类:不能实例化
//2.它的构造器不能带参数! 即:不能添加()trait Shentihao{//具体属性var KM_i = 5//抽象属性var sports:String//具体方法def say(): Unit = {}//抽象方法def run
}
class Student extends Shentihao{var sports = "跳绳"def run: Unit = {println("1000m 在4.5分钟内跑完")}
}
object zjh {def main(args: Array[String]): Unit = {var s1 = new Student()// s1.}
}
trait多继承
//多继承//美貌
trait Beauty{val leg:Double
}//智慧
trait Wisdom{val Eq:Int
}
//一个类:实现了两特质。用with隔开
//多个特质可以交换顺序
class Girl extends Beauty with Wisdom{val leg = 180val Eq = 180override def toString: String = s"leg=${leg},eq=${Eq}"
}object tnt {def main(args: Array[String]): Unit = {val girl = new Girl()println(girl)}}
多重继承
//继承多个特质时,加载的顺序
//1.先父后子
//2.从左到右
trait A051{println("1")
}
trait B051{println("2")
}
class AB extends A051 with B051{println("AB")
}
object lll {def main(args: Array[String]): Unit = {new AB()}
}
trait A051{println("A051")}trait AA051 extends A051{println("AA051")}trait AB051 extends A051{println("AA051")}trait B051{println("B051")}trait BA051 extends B051{println("BA051")}trait BB051 extends B051{println("BB051")}class AB extends AA051 with BA051 with AB051 with BB051{println("AB")
}
object yyy {def main(args: Array[String]): Unit = {new AB()}}
//答案:A051 AA051 B051 BA051 AA051 BB051 AB
多重继承的惰性求值
import java.io.PrintWriter
//演示一个经典报错:空指引异常trait FileLogger{//抽象属性,没有=val filename:Stringprintln("父类",filename)val fileout = new PrintWriter(filename)//用来把 msg 写入到对应的文件中def log(msg:String): Unit = {fileout.println(msg)fileout.println()}
}
class Test211 extends FileLogger{val filename = "2024-10-28.txt"println("子类",filename)
}object zzx {def main(args: Array[String]): Unit = {val t1 = new Test211()t1.log("test!")}
}
import java.io.PrintWriter
//演示一个经典报错:空指引异常trait FileLogger{//抽象属性,没有=val filename:Stringprintln("父类",filename)//lazy 表示,不立刻求值,而是等到这个变量被使用的时候,去求值lazy val fileout = new PrintWriter(filename)//用来把 msg 写入到对应的文件中def log(msg:String): Unit = {fileout.println(msg)fileout.println()}
}
class Test211 extends FileLogger{val filename = "2024-10-28.txt"println("子类",filename)
}object zzx {def main(args: Array[String]): Unit = {val t1 = new Test211()t1.log("test!")}
}
匿名类:提前定义
import java.io.PrintWritertrait FileLogger{//抽象属性,没有=val filename:Stringprintln("父类",filename)val fileout = new PrintWriter(filename)//用来把 msg 写入到对应的文件中def log(msg:String): Unit = {fileout.println(msg)fileout.println()}
}
class Test211 extends FileLogger{val filename = "2024-10-28.txt"println("子类",filename)
}object zzx {def main(args: Array[String]): Unit = {
// val t1 = new Test211()//匿名类,提前定义val t1 = new { val filename="2024-10-29.txt"} with FileLoggert1.log("test!" * 10)}