一、类的定义
class Counter(参数列表){
//这里定义类的字段和方法
}
class Counter {
var value = 0
def increment(step:Int):Unit = {value += step}
def current():Int = {value}
}
//类的实例化
object test {
def main(args: Array[String]): Unit = {
val myCounter = new Counter
myCounter.value = 5 //访问字段
myCounter.increment(3) //调用方法
println(myCounter.current())
//调用无参方法时可以省略方法名后的括号
}
}
out:8
二、类成员的可见性
Scala默认可见性就是公有的。
Scala私有:
- private
本类型可见
嵌套类型可见 - protected
本类型可见
其他继承类型可见
value
:读取
value_=
:修改
类成员的可见性实例:
class Counter2 {
private var privateValue = 0
def value = privateValue
def value_=(newValue: Int): Unit = {
if (newValue > 0) privateValue = newValue
}
def increment(step: Int): Unit = {value += step}
def current(): Int = {value}
}
object test2{
def main(args: Array[String]): Unit = {
val myCounter2=new Counter2
myCounter2.value_=(3)
//myCounter2.value=3等效于myCounter2.value_=(3)
println(myCounter2.value)
}
}
out:3
三、方法的定义方式
def 方法名(参数列表):返回结果类型(不返回时默认Unit)={方法体}
在参数列表中:
- 参数是不能用val和var作为前缀去修饰。
- 没有参数的方法在定义的时候是可以圆括号省略掉的。
- 一个方法如果只有一个参数可以省略圆点而采用中缀操作符调用方法。(此时a.+(b)等价a+b)
四、构造器
- 主构造器:类本身的定义体
- 辅助构造器:继续不断去定义
1.主构造器:
可以在主构造器(类)中加var
或者val
修饰相关参数,加了修饰后的Scala类会自动创建相关的内部成员。
scala> class Counter(var name:String)//定义一个带字符串参数的简单类
defined class Counter
scala> var mycounter=new Counter("Runner")
mycounter: Counter = Counter@539935ed
scala> println(mycounter.name)//调用读方法
Runner
scala> mycounter.name_=("Timer")//调用写方法
scala> mycounter.name="Timer"//更直观地调用写方法,和上句等效
mycounter.name: String = Timer
2.辅助构造器
辅助构造器第一个表达式:调用此前已经定义的辅助构造器,调用此前已经定义的主构造器。
辅助构造器调用形式:
This(参数列表)
类(构造器)实例:
class Counter3 {
private var value = 0
private var name = ""
private var step = 1 //计算器的默认递进步长
println("the main constructor")
def this(name: String) { //第一个辅助构造器
this() //调用主构造器
this.name = name
printf("thr first auxiliary constructor,name:%s\n", name)
}
def this(name: String, step: Int) { //第二个辅助构造器
this(name) //调用前一个辅助构造器
this.step = step
printf("the second auxiliary constructor,name:%s,step:%d\n", name, step)
}
def increment(step: Int): Unit = {value += step}
def current(): Int = {value}
}
object test3 {
def main(args: Array[String]): Unit = {
val c1 = new Counter3()
println("----------------------------")
val c2 = new Counter3("the 2nd Counter")
println("----------------------------")
val c3 = new Counter3("the 3nd Counter", 2)
}
}
out:
the main constructor
----------------------------
the main constructor
thr first auxiliary constructor,name:the 2nd Counter
----------------------------
the main constructor
thr first auxiliary constructor,name:the 3nd Counter
the second auxiliary constructor,name:the 3nd Counter,step:2