spark

scala基础(4)

2019-08-01  本文已影响0人  Jasmine晴天和我

类的创建

class Counter{
      //这里定义类的字段和方法
}
//用new关键字来生成对象
new Counter //或者new Counter()
//给类添加字段和方法
class Counter {
    private var value = 0 //私有变量,只有在类内部可以访问该字段 
    def increment(): Unit = { value += 1}
    def current(): Int = {value}
} //Unit表示返回空

class Counter {
    private var value = 0
    def increment(): Unit = value += 1 //去掉了大括号
    def current(): Int = {value}  //作为对比,这里依然保留大括号
}

class Counter {
    private var value = 0
    def increment() {value += 1} //去掉了返回值类型和等号,只保留大括号
    def current(): Int = {value} //作为对比,这里依然保留原来形式
}

val myCounter = new Counter
myCounter.increment() //或者也可以不用圆括号,写成myCounter.increment
println(myCounter.current)
//Scala在调用无参方法时,是可以省略方法名后面的圆括号的。
上一篇 下一篇

猜你喜欢

热点阅读