scala(物件)-第三天
1、面向物件概述
java:
封裝:屬性、方法封裝到類中
User:int id,String name,Date birthday
繼承:
多型:
2、類的定義與使用
def main(args:Array[String]):Unit={
val person = new People()
person.name = "Messi"
//person.age=30 //會報錯,因為是val,沒有setter方法,只有getter方法
println(person.name + " .. " +person.age)
person.eat
person.watchFootbal("barcelona")
person.printInfo
//println(person.gender) 會報錯,因為gender被private【this】修飾
}
class People{
var name:String = ""
val age:Int = 10
private [this] val gender = "male"
def printInfo():Unit = {
println("gender: "+ gender)
}
def eat():String = {
name + "eating"
}
def watchFootball(teamName: String): Unit={
println(name + " is watching match of " + teamName)
}
}
3、構造器
object ConstructorApp{
main{
val person = new Person("zhangsan",30)
val person2 = new Person("ting",18,"M")
}
}
//主構造器,跟在類名後面的(val name:String, val age:Int)叫做主構造器
class Person(val name:String, val age:Int){
println("Person enter...")
val gender:String = _
//附屬構造器,
def this(name:String,age:Int,gender:String){
this(name,age) //附屬構造器的第一行程式碼必須要呼叫主構造器或者其他附屬構造器
this.gender = gender
}
def eat()="eat"
}
4、繼承與重寫
main{
val student = new Student("messi",18,"Math")
}
class Student(name:String, age:Int,val major:String) extends Person(name,age){
//子類特有的引數必須寫val或var,不然會報錯
//先呼叫父類構造器,再呼叫子類構造器
override def eat()="override def eat"
}
5、抽象類
類的一個或者多個方法沒有完整的實現(只有定義,沒有實現)
main{
val student = new Student2()
println(student.name+student.age)
}
abstract class Person2{
def speak
val name:String
val age:Int
}
class Student2 extends Person2{
override def speak: Unit={
println("speak")
}
override val name:String = "messi"
override val age:Int = 18
}
6、伴生類與伴生物件
//如果有一個class,還有一個與class同名的object
//那麼就稱這個objcet是class的伴生物件,class是object的伴生類
//伴生類
class ApplyTest{
}
//伴生物件
object ApplyTest{
}
7、apply
object{
main{
for(i<-1 to 10){
ApplyTest.incr
}
println(AppkyTest.count) //10, 說明object本身就是一個單例物件
val b = ApplyTest() //==>Object.apply
val c = new ApplyTest() //
c() // ===>class.apply
//類名() ==> Object.apply
//物件() ==> Class.apply
}
}
//伴生類
class ApplyTest{
def apply()={
在objcet中的apply中new class
new ApplyTest
}
}
//伴生物件
object ApplyTest{
var count = 0
def incr = {
count+=1
}
//最佳實踐,在Object的apply方法中去new Class
def apply():ApplyTest={
在objcet中的apply中new class
new ApplyTest
}
}
8、case class
//通常用在模式匹配
main{
pintln(Dog("wangcai").name)
}
//case class 不用new
case class Dog(name:String)
9、trait
相當於介面
xxx extends ATrait with BTrait with ...