原创文章,转载请注明出处!

原文地址: http://www.ptbird.cn/2016/07/19/scala-chuji-demo-08/

There I am,in the world more exciting!

by postbird

www.ptbird.cn


08对象和伴生对象


 
package com.ptbird.scala /** * Created by postbird on 2016/5/25. */ class University{ val id= University.StuNo() val id2 = University.stuNo //可以访问伴生对象的私有成员 private var number=0 def aClass(number:Int): Unit ={ this.number+=number } } object University { private var stuNo = 0 //属于静态变量,会随着代码的操作改变值的内容 def StuNo() = { stuNo += 1 stuNo } } //如果创建对象的时候没有使用new class的方式,则默认调用的就是伴生对象 object ObjectTest { def main(args: Array[String]): Unit = { println(University.StuNo()) println(University.StuNo()) var stu = new University() println(stu.id +" "+stu.id2) // 1 // 2 // 3 3 } }