Scala中class和object的區別

一、classjava

        scala的類和C#中的類有點不同,諸如: 聲明一個未用priavate修飾的字段 var age,scala編譯器會字段幫咱們生產一個私有字段和2個公有方法get和set ,這和C#的簡易屬性相似;若使用了private修飾,則它的方法也將會是私有的。這就是所謂的統一訪問原則。app

  1. //類默認是public級別的  
  2. class Person{  
  3.   var age=18  //字段必須得初始化()  
  4.   def Age=age //這個是方法,沒有參數能夠省略()  
  5.   def incremen(){this.age+=1}  
  6. }  
  7.   
  8.   
  9. class Student{  
  10.   var age=20     //底層編譯器會自動爲私有的age添加get和set的公有方法,能夠理解爲僞public類型  
  11.   private[this] var gender="male" //private[this] 只有該類的this可使用  
  12.   private var name="clow" //聲明瞭private,底層編譯器會自動爲私有的name添加get和set的私有方法  
  13.   //可是能夠本身定義屬性方法  
  14.   def getName=this.name  
  15.   def setName(value:String){this.name=value}  
  16. }  
  17.   
  18. //構造器的使用  
  19. class Teacher {  
  20.   var age: Int = _  
  21.   var name: String = _  //能夠預留  
  22.   
  23.   //重載的構造器和C#裏面的public Teacher(){}相似  
  24.   def this(age: Int, name: String){  
  25.     this() //必須得調用一次主構造器  
  26.     this.age=age  
  27.     this.name=name  
  28.   }  
  29. }  

二、scala沒有靜態的修飾符,但object下的成員都是靜態的 ,如有同名的class,這其做爲它的伴生類。在object中通常能夠爲伴生類作一些初始化等操做,如咱們經常使用的val array=Array(1,2,3)  (ps:其使用了apply方法)this

  1. object Dog{  
  2.   private var age=0  
  3.   def Age={  
  4.     age+=1  
  5.     age  
  6.   }  
  7. }  
  8.   
  9. class Dog{  
  10.   var age1=Dog.age //Dog.age是object Dog的私有字段。這不由讓我回想起了C++的友元類  
  11. }  

三、Apply的使用,怎麼解釋呢? 仍是來看看怎麼用它來實現單例模式spa

  1. class ApplyTest private{  //添加private隱藏構造器  
  2.   def sayHello(){  
  3.     println("hello jop")  
  4.   }  
  5. }  
  6.   
  7. object ApplyTest{  
  8.   var instant:ApplyTest=null  
  9.   def apply() ={  
  10.     if(instant==null) instant=new ApplyTest  
  11.     instant  
  12.   
  13.   }  
  14. }  
  15.   
  16. object ApplyDemo {  
  17.   def main(args:Array[String]){  
  18.       val t=ApplyTest()  
  19.       t.sayHello()  
  20.   }  
  21. }  
相關文章
相關標籤/搜索