本篇主要介绍Scala中的class
5.1 简单的类和无参数方法
class Counter {
private var value = 0 // You must initialize the field
def increment() { value += 1 } // Methods are public by default
def current() = value
}
变量需要初始化,方法默认是public
。
一个Scala源文件中可以包含**多个**class
,所有的class
都是public
的。
val myCounter = new Counter // Or new Counter()
myCounter.increment()
println(myCounter.current)
建议不会改变对象的方法,调用时省略()
;会改变对象的,不省略()
。
如果方法在定义时没有写()
,则调用时也不需要()
。
5.2 属性的getter和setter
Scala对每个域,都提供getter和setter。域的getter和setter方法,分别为变量名
和变量名_=
。
println(fred.age) // Calls the method fred.age()
fred.age_=(21) // Calls fred.age_=(21)
public
的变量的getter和setter都是public
,private
变量的都是private
。
5.3 只有getter的属性
对于一个val
,只会生成getter方法。
5.4 Object-Private域
class Counter {
private var value = 0
def increment() { value += 1 }
def isLess(other : Counter) = value < other.value
// Can access private field of other object
}
在Scala中,一个方法可以访问这个类所有对象的private域。
private[this] var value = 0 // Accessing someObject.value is not allowed
用private[this]
修饰后,方法只可以访问对象自己的private
变量。这种访问权限称为Object-Private。
5.5 Bean属性
import scala.reflect.BeanProperty
class Person {
@BeanProperty var name: String = _
}
用@BeanProperty
标记一个域,则会生成对应域的getFoo/setFoo
方法。
5.6 辅助构造函数(Auxiliary Constructors)
Scala中允许有任意多的构造函数。有一个主构造函数(primary constructor),和任意多的辅助构造函数(Auxiliary Constructors)。
辅助构造函数,与Java和C++中的构造函数很相似,有两点不同:
- 辅助构造函数通过
this
来调用。 - 每一个辅助构造函数必须以一个已经定义的辅助构造函数,或者主构造函数开始。
class Person {
private var name = ""
private var age = 0
def this(name: String) { // An auxiliary constructor
this() // Calls primary constructor
this.name = name
}
def this(name: String, age: Int) { // Another auxiliary constructor
this(name) // Calls previous auxiliary constructor
this.age = age
}
}
val p1 = new Person // Primary constructor
val p2 = new Person("Fred") // First auxiliary constructor
val p3 = new Person("Fred", 42) // Second auxiliary constructor
5.7 主构造函数(Primary Constructor)
class Person(val name: String, val age: Int) {
// Parameters of primary constructor in (...)
...
}
主构造函数在类定义的同时定义。参数直接放在类名的后面,参数会直接变为类的域。
上面这一行多的Scala代码,与下面这几句Java效果相同:
public class Person { // This is Java
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String name() { return this.name; }
public int age() { return this.age; }
...
}
主构造函数执行类定义中的所有语句。
class Person(val name: String, val age: Int) {
println("Just constructed another person")
def description = name + " is " + age + " years old"
}
上面这个类,在构建时会打印相应的字符串。
5.8 嵌套类(Nested Classes)
import scala.collection.mutable.ArrayBuffer
class Network {
class Member(val name: String) {
val contacts = new ArrayBuffer[Member]
}
private val members = new ArrayBuffer[Member]
def join(name: String) = {
val m = new Member(name)
members += m
m
}
}
val chatter = new Network
val myFace = new Network
Scala允许在类中定义类。chatter.Member
和myFace.Member
是不同的类。