一、classjava
scala的類和C#中的類有點不同,諸如: 聲明一個未用priavate修飾的字段 var age,scala編譯器會字段幫咱們生產一個私有字段和2個公有方法get和set ,這和C#的簡易屬性相似;若使用了private修飾,則它的方法也將會是私有的。這就是所謂的統一訪問原則。app
- class Person{
- var age=18
- def Age=age
- def incremen(){this.age+=1}
- }
-
-
- class Student{
- var age=20
- private[this] var gender="male"
- private var name="clow"
-
- def getName=this.name
- def setName(value:String){this.name=value}
- }
-
- class Teacher {
- var age: Int = _
- var name: String = _
-
-
- def this(age: Int, name: String){
- this()
- this.age=age
- this.name=name
- }
- }
二、scala沒有靜態的修飾符,但object下的成員都是靜態的 ,如有同名的class,這其做爲它的伴生類。在object中通常能夠爲伴生類作一些初始化等操做,如咱們經常使用的val array=Array(1,2,3) (ps:其使用了apply方法)this
- object Dog{
- private var age=0
- def Age={
- age+=1
- age
- }
- }
-
- class Dog{
- var age1=Dog.age
- }
三、Apply的使用,怎麼解釋呢? 仍是來看看怎麼用它來實現單例模式spa
- class ApplyTest private{
- def sayHello(){
- println("hello jop")
- }
- }
-
- object ApplyTest{
- var instant:ApplyTest=null
- def apply() ={
- if(instant==null) instant=new ApplyTest
- instant
-
- }
- }
-
- object ApplyDemo {
- def main(args:Array[String]){
- val t=ApplyTest()
- t.sayHello()
- }
- }