val、var
package com_1030class Person {var name:String="rose"def sum(n1:Int,n2:Int):Int={n1+n2}
}
object Person{def main(args: Array[String]): Unit = {//创建person对象var person=new Person()println(person.sum(10,20))//30println(person.name)person.name="www"println(person.name)//可以new,内存地址可以变person=new Person()//声明引用数据类型的常量val person2=new Person()println(person2.name)person2.name="rose456"println(person2.name)//不可以new,内存地址不能变//不可以为引用数据类型的常量重新分配内存//×××----------person2=new Person()}
}
辅助构造器、主构造器
package com_1030class Person1{var name:String=_var age:Int=_//定义辅助构造器def this(name:String){//辅助构造器必须调用主构造器this()//给name赋值this.name=nameprintln("辅助构造器")}
def this(age:Int){//调用主构造器this()this.age=ageprintln("辅助构造器")
}def this(name:String,age:Int){this()this.name=namethis.age=ageprintln("辅助构造器")}println("主构造器")}
object Person1{def main(args: Array[String]): Unit = {//创建对象var p1=new Person1("rose")println(p1.name)var p2=new Person1(20)println(p2.age)var p3=new Person1("jack",28)println(p3.name+":::"+p3.age)}}
继承
package com_1030class Person2 (nameParam:String){var name:String=nameParamvar age:Int=_//创建辅助构造器def this(name:String,age:Int){this(name)//给age赋值this.age=ageprintln("父类的辅助构造器")}
println("父类的主构造器")
}
//创建子类继承Person
class Emp(nameParam:String,ageParam:Int) extends Person2(nameParam,ageParam){
var empNo:Int=_//创建子类的辅助构造器def this(name:String,age:Int,empNo:Int){//调用主构造this(name,age)this.empNo=empNoprintln("子类的辅助构造器")}println("子类的主构造器")
}object Emp{def main(args: Array[String]): Unit = {var emp=new Emp("rose",25,1002121)}
}