抽象类(abstract class):
类的一个或多个方法没完整的定义
声明抽象方法不需要加abstract关键字,只需要不写方法体
子类重写父类的抽象方法时 不需要加override
父类可以声明抽象字段(没有初始值的字段)
子类重写父类的抽象字段时 不需要加override
object Basic3 {
def main(args:Array[String]): Unit ={
val s1 = new Student1
s1.speak
println(s1.name + ":" + s1.age)
}
}
abstract class Person1{
def speak
val name:String
val age:Int
}
class Student1 extends Person1{
def speak: Unit ={
println("speck!!!")
}
val name = "aaa"
val age = 100
}
输出结果:

特质(trait)(可以当做可以实现具体方法的接口)
字段和行为的集合
混入类中
通过with关键字,一个类可以扩展多个特质
当做接口
带有具体实现的接口
带有特质的对象
特质从左到右被构造
def main(args:Array[String]): Unit ={
val t = new Test
t.test
}
}
trait Logger{
def log(msg:String): Unit ={
println("log " + msg)
}
}
class Test extends Logger{ //如果在类中混入第一个trait且该类没有继承任何其他类,则需要使用extends
def test: Unit ={
log("xxx")
}
}
输出结果:

object Basic3 {
def main(args:Array[String]): Unit ={
val acc = new MyAccount
acc.save
//对象加trait,要注意MyAccount加了ConsoleLogger,而MessageLogger继承了ConsoleLogger,
//若MessageLogger没有继承ConsoleLogger则MyAccount的对象无法加MessageLogger trait
val acc1 = new MyAccount with MessageLogger
acc1.save
}
}
trait ConsoleLogger{
def log(msg:String): Unit ={
println("save money " + msg)
}
}
trait MessageLogger extends ConsoleLogger{
override def log(msg:String): Unit ={ //父trait的log函数不是抽象方法,所以需加override
println("save money to bank: " + msg)
}
}
abstract class Account{
def save
}
class MyAccount extends Account with ConsoleLogger {
def save: Unit ={
log("100")
}
}
输出结果:

apply()方法
object Basic4 {
def main(args:Array[String]): Unit ={
val a = ApplyTest() //类名加括号调用object的apply方法
a.test
val t = new ApplyTest
println(t()) //对象加括号调用类的apply方法
println(t)
}
}
class ApplyTest{
def apply() = "APPLY"
def test: Unit ={
println("test")
}
}
object ApplyTest{
def apply() = new ApplyTest()
}
输出结果:

模式匹配
object Basic5 {
def main(args:Array[String]): Unit ={
val value = 1
//匹配到合适的会立刻返回
val result = value match{
case 1 => "one"
case 2 => "two"
case _ => "some other number"
}
println("result of match is: " + result)
val result1 = value match {
case i if i == 1 => "one"
case i if i == 2 => "two"
case _ => "some other number"
}
println("result of match is: " + result1)
t(1)
t("1")
t(1.0)
}
def t(obj:Any) = obj match{
case x:Int => println("Int")
case s:String => println("String")
case _ => println("unknown type")
}
}
输出结果:

本文介绍了Scala编程中的抽象类、特质及其用法,包括抽象方法和字段的定义、子类的继承与重写。同时展示了特质作为接口和带有具体实现的特性,以及如何在类中混合多个特质。此外,还探讨了apply方法的使用以及模式匹配的概念和应用,展示了如何在代码中进行值匹配和条件判断。
795

被折叠的 条评论
为什么被折叠?



