val、var
package com_1030
class 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))//30
println(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_1030
class Person1{
var name:String=_
var age:Int=_
//定义辅助构造器
def this(name:String){
//辅助构造器必须调用主构造器
this()
//给name赋值
this.name=name
println("辅助构造器")
}
def this(age:Int){
//调用主构造器
this()
this.age=age
println("辅助构造器")
}
def this(name:String,age:Int){
this()
this.name=name
this.age=age
println("辅助构造器")
}
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_1030
class Person2 (nameParam:String){
var name:String=nameParam
var age:Int=_
//创建辅助构造器
def this(name:String,age:Int){
this(name)
//给age赋值
this.age=age
println("父类的辅助构造器")
}
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=empNo
println("子类的辅助构造器")
}
println("子类的主构造器")
}
object Emp{
def main(args: Array[String]): Unit = {
var emp=new Emp("rose",25,1002121)
}
}