* 类
~~~
class People{
//_是占位符,是默认值
var name:String = _
val age:Int =10
//private[this] 表示只能在本类使用
private [this] val gender = "male"
def printInfo()={
println("gender:"+gender)
}
def eat():String = {
name+"eat..."
}
def watchBall(team:String)={
println(name+" look: "+team);
}
}
~~~
* 构造器
~~~
//主构造器
class Person(val name:String,val age:Int){
println("enter")
val school = "ustc"
var gender:String = _
//附属构造器
def this(name:String,age:Int,gender:String)={
//附属构造器第一行必须调用主构造器或者其他构造器
this(name,age);
this.gender = gender;
}
println("leave")
}
val person = new Person("zhangsan",30)
println(person.name+":"+person.age+":"+person.school)
val person2 = new Person("Bizz",30,"男")
println(person2.name+":"+person2.age+":"+person2.school+":"+person2.gender)
~~~
* 继承
~~~
//如果父类有的属性,不用价var,没有的一定要加
class Student(name:String,age:Int,var major:String) extends Person(name, age){
println("senter")
println("sleave")
}
~~~
* 重写
~~~
class Student(name:String,age:Int,var major:String) extends Person(name, age){
println("senter")
//重写父类的属性和方法,要使用override关键字
override val school = "peking"
override def toString: String = {
"my tostring"
}
println("sleave")
}
~~~
* 抽象类
~~~
abstract class Person{
def speak
val name:String
val age:Int
}
class Teacher extends Person{
override def speak: Unit = println("say sth")
override val name: String = "Bizz"
override val age: Int = 28
}
~~~
* 伴生类和伴生对象
~~~
//伴生类
class ApplyTest{
def apply(): ApplyTest = {
println("class apply")
new ApplyTest()
}
}
//同名的class和object互为伴生
//伴生对象
//object是一个单例对象
object ApplyTest{
var count =0;
def incr = {
count = count+1
}
def apply() = {
println("obj apply")
new ApplyTest()
}
//会调用对象的apply
val b = ApplyTest()
val c = new ApplyTest()
//会调用类的apply
c()
/*类名()==>obj.apply
* 对象()==>class.apply
*
* */
~~~
* case Class
~~~
object CaseClassApp{
def main(args: Array[String]): Unit = {
println(Dog("小雨").name)
}
}
//case class 不用new
//通常用在模式匹配
case class Dog(name:String)
~~~
* trait (相当于接口)