1.函数基础操作(成员变量为private的情况)
- private形式的变量不能在外界进行访问
scala> class c{
| private var c = "spark"
| def sayName (){println(c)}
| def getName = c
| }
defined class c
scala> val d = new c()
d: c = c@15ef322
scala> d.sayName()
spark
scala> d.getName
res5: String = spark
scala> d.c
<console>:16: error: variable c in class c cannot be accessed in c
d.c
- var形式的变量scala会自动给变量添加get、set方法,直接访问即可
scala> class b {
| var name = "scala"
| def sayName (){println(name)}
| def getName = name
| }
defined class b
scala> val c = new b()
c: b = b@127a7e
scala> c.name
res1: String = scala
scala> c.getName
res2: String = scala
scala> c.sayName()
scala
- 复写get set 方法时增加 name_方法
scala> :paste
// Entering paste mode (ctrl-D to finish)
class Person{
private var myName = "Flink"
def name = this.myName
def name_=(newName : String){
myName = newName
println ("newName:"+myName)}
}
// Exiting paste mode, now interpreting.
defined class Person
scala> val p = new Person()
p: Person = Person@d190be
scala> p.name
res12: String = Flink
scala> p.name = "Spark"
newName:Spark
p.name: String = Spark
scala> p.name
res13: String = Spark
2.Object 和 Class函数的具体区别
- object和class一般同名存在
- object一般是静态变量,相当于java中static
class中存放一般的方法,相当于java类
object为伴生对象
- class为伴生类
3.Trait
- Trait可以被作为接口或者抽象类来使用
- 类继承Trait后,必须实现其中的抽象方法,不需要使用override关键字,Scala支持多重继承Trait,使用with关键字。
- trait可以包含一些很多类都通用的功能,如打印日志等,在Spark中也使用Trait定义了通用的日志打印方法。
scala> :paste
// Entering paste mode (ctrl-D to finish)
trait HelloTrait {
def sayHello(name : String)
}
trait MakeFirendsTrait {
def makeFirends(p : Person)
}
class Person(val name : String) extends HelloTrait with MakeFirendsTrait{
def sayHello(name : String)= println("hello::::::"+name)
def makeFirends(p : Person)= println("hello1:::::::"+p.name)
}
// Exiting paste mode, now interpreting.
defined trait HelloTrait
defined trait MakeFirendsTrait
defined class Person
scala> val p = new Person("aaaa")
p: Person = Person@ea0d65
scala> p.sayHello("aaa")
hello::::::aaa
scala> val p1 = new Person("bbb")
p1: Person = Person@f8d452
scala> p.makeFirends(p1)
hello1:::::::bbb