1.对象私有字段
1)private
- class Counter(num: Int) {
- private var value = 0
-
- def increment() = {
- value += 1
- }
-
- def isLess(other: Counter) = value < other.value
-
- def printlnNum(): Unit = {
- println("num: " + num)
- }
-
- // def isLess(other: Counter) = value
- }
-
-
-
- object Counter {
- def main(args: Array[String]): Unit = {
- /*
- * 1. 方法可以访问类的所有对象的私有字段
- */
- val counter1 = new Counter(3)
- counter1.increment()
-
- val counter2 = new Counter(4)
- counter2.increment()
- counter2.increment()
-
- println(counter1.isLess(counter2)) // 结果:true 因为1<2
- }
- }
解释:方法可以访问类的所有对象的私有字段。 所以即使value字段是private的,非当前对象other对象也可以访问到value字段。
2) private[this]

解释:私有字段加上[this]修饰符,可以字面简单的理解为该字段是私有的(private)并且只限当前对象[this]使用。 所有other对象访问不到 value 字段。
3)类构造参数
- class Counter(num: Int) {
- private var value = 0
-
- def increment() = {
- value += 1
- }
-
- def isLess(other: Counter) = value < other.value
-
- // def isLess(other: Counter) = value
- def subNum(other: Counter): Int = {
- num - other.num
- }
- }
// 测试- object Counter {
- def main(args: Array[String]): Unit = {
- val counter1 = new Counter(3)
- val counter2 = new Counter(4)
-
- println(counter1.subNum(counter2))
- }
- }
编译会报 error: value num is not a member of cn.XX.quickScala.jurisdiction.Counter。
解释:类构造参数不是字段,所以每个类的构造参数都只能当前对象this访问,是不能在当前类中访问另一个同一个类对象的构造参数的【虽然能点出来,但编译通不过】
解决方案: 加字段,将类构造参数赋值给字段

结果是 -1
总结:
private[this] 字段 和 类构造参数都是只能在当前对象范围内访问到,是访问不到同一个类的另一个对象的 private[this]字段 或 类构造参数的。
但需要注意,访问另一个对象的private[this] 编译器直接会提示找不到,编程的时候是 . 不出来的。而访问另一个对象的 类构造参数时,是可以 . 出来的,但编译通不过。
private 所有的类对象都可以访问到,不管是当前this对象还是传入的外围同一个类对象。 同java一样,private字段是只能在当前类型访问的,在类外面是无法访问到的。