0007.Scala类的属性和对象私有字段实战详解

来源:互联网 发布:嵌入式好还是java好 编辑:程序博客网 时间:2024/06/06 17:15
package com.jn.scala.hello

/**
 * @author jiangning
 */
//类默认就是public的
class Person {
//  1.定义变量必须有初始值
  private var age = 0
  def increment(){age += 1}
  def current = age
}

class Student{
//  2.声明一个属性age,属性是private级别的默认
//  默认会自动生成get与set方法,不用像java一样写get与set方法
  var age = 0
  private var privateAge = 0
  private[ this] var privateThisAge = 0
  def ages = privateAge
//  默认只有get方法,没有set方法
  val name = "Scala"
//  class内部可以调用私有属性,
  def isYounger(other: Student) = privateAge < other.privateAge
 
//  def isYounger(other: Student) = privateThisAge < other.privateThisAge
}
object HelloOOP {
  def main(args: Array[ String]) {
    val person = new Person()
    person.increment()
    person.increment()
    println(person.current)
   
    val student = new Student()
//  默认定义一个set方法  def age_=(x$1: Int ): Unit
    student.age = 10
//  默认定义一个get方法  def age: Int ,通过age方法取出age的值,
    println(student.age)
   
    println(student.name)
//    student.name = "good"//不能进行值的改变,
  }
}
0 0
原创粉丝点击