scala中的伴生类 伴生对象说明

1、代码如下:

[java]  view plain  copy
 print ?
  1. package com.yy.oop  
  2.   
  3. /** 
  4.  * 伴生类和伴生对象 
  5.  * class Student是伴生对象Object Student的伴生类 
  6.  * object Student是伴生类class Student的伴生对象  
  7.  */  
  8.   
  9.   
  10. //伴生类  
  11. class Student(var name:String,var address:String){  
  12.     
  13.   private var phone="110"  
  14.   //直接访问伴生对象的私有成员  
  15.   def infoCompObj() = println("伴生类中访问伴生对象:" + Student.sno)  
  16. }  
  17.   
  18. //伴生对象  
  19. object Student {  
  20.     
  21.   private var sno:Int = 100  
  22.   def incrementSno()={  
  23.       
  24.     sno += 1 //加1  
  25.     sno  //返回sno  
  26.   }  
  27.   def main(args: Array[String]): Unit = {  
  28.       
  29.     println("单例对象:" + Student.incrementSno()) //单例对象  
  30.       
  31.     //实例化伴生类  
  32.     val obj = new Student("yy","bj")  
  33.     obj.infoCompObj();  
  34.   }  
  35. }  

2、结果如下

[plain]  view plain  copy
 print ?
  1. 单例对象:101  
  2. 伴生类中访问伴生对象:101  

3、scala apply 

[java]  view plain  copy
 print ?
  1. package com.yy.oop  
  2.   
  3. /** 
  4.  * 伴生类和伴生对象 
  5.  * class Student是伴生对象Object Student的伴生类 
  6.  * object Student是伴生类class Student的伴生对象  
  7.  */  
  8.   
  9.   
  10. //伴生类  
  11. class Student(var name:String,var address:String){  
  12.     
  13.   private var phone="110"  
  14.   //直接访问伴生对象的私有成员  
  15.   def infoCompObj() = println("伴生类中访问伴生对象:" + Student.sno)  
  16. }  
  17.   
  18. //伴生对象  
  19. object Student {  
  20.     
  21.   private var sno:Int = 100  
  22.   def incrementSno()={  
  23.       
  24.     sno += 1 //加1  
  25.     sno  //返回sno  
  26.   }  
  27.     
  28.   //定义apply方法,实例化伴生类  
  29.   def apply(name1:String,address1:String)= new Student(name1,address1)  
  30.     
  31.     
  32.   def main(args: Array[String]): Unit = {  
  33.       
  34.     println("单例对象:" + Student.incrementSno()) //单例对象  
  35.       
  36.     //实例化伴生类  
  37.     val obj = new Student("yy","bj")  
  38.     obj.infoCompObj();  
  39.       
  40.     println("通过伴生对象的apply方法访问伴生类成员:")  
  41.     val obj2 = Student("yy_apply","bj_apply"//实际是通过apply方法进行了对象实例化,避免了手动new对象  
  42.     println(obj2.name)  
  43.     println(obj2.address)  
  44.   }  
  45. }  

结果如下:

[plain]  view plain  copy
 print ?
  1. 单例对象:101  
  2. 伴生类中访问伴生对象:101  
  3. 通过伴生对象的apply方法访问伴生类成员:  
  4. yy_apply  
  5. bj_apply  
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值