1 抽象类
package com.lihaogn
object AbstractApp {
def main(args: Array[String]): Unit = {
val student=new Students2()
println(student.name)
student.speak
}
}
/**
* 类的一个或者多个方法没有完整的实现(只有定义,没有实现)
*/
abstract class Person2 {
def speak
val name: String
val age: Int
}
// 子类实现抽象类
class Students2 extends Person2 {
override def speak: Unit = {
println("speak")
}
override val name: String = "lisi"
override val age: Int = 20
}
2 伴生类与伴生对象
package com.lihaogn
object ApplyApp {
def main(args: Array[String]): Unit = {
for (i <- 1 to 10) {
ApplyTest.incr
}
println(ApplyTest.count)
val b = ApplyTest() // ==> Object.apply
println("==================")
// new一个class对象
val c = new ApplyTest()
println(c)
c()
// 类名() ==> Object.apply
// 对象() ==> Class.apply
}
}
/**
* 伴生类与伴生对象
* 若有一个class和其同名的object
* 则就称object是class的伴生对象,class是object的伴生类
*/
class ApplyTest {
def apply() = {
println("Class ApplyTest apply ....")
}
}
object ApplyTest {
println("Object ApplyTest entering....")
var count = 0
def incr = {
count = count + 1
}
// 最佳实践:在Object的apply方法中去new class
def apply() = {
println("Object ApplyTest apply ....")
// 在Object中new一个class
new ApplyTest
}
println("Object ApplyTest leaving....")
}
运行结果:
Object ApplyTest entering....
Object ApplyTest leaving....
10
Object ApplyTest apply ....
==================
com.lihaogn.ApplyTest@75bd9247
Class ApplyTest apply ....
3 case class
package com.lihaogn
object CaseClassApp {
def main(args: Array[String]): Unit = {
println(Dog("wangwang").name)
}
}
// case class 不用new
// 通常用在模式匹配里
case class Dog(name: String)
4 Trait
类似于Java中的接口
// 第一个Trait用extends,其他的用with
class class-name(xxx:xxx) extends Cloneable with Logging with ....