scala 中的修饰符

 1 package cn.scala_base.oop.scalaclass
 2 import scala.beans.BeanProperty;
 3 /**
 4  * scala中的field,类中定义的是方法,函数不依赖于类存在
 5  *
 6  */
 7 class Student {
 8   //没有修饰符的var变量,在编译时会被声明为private类型,但提供公共的get和set方法,即name,name_=,但调用赋值时采用 s.name=xxx的形式
 9   var name = "tele";
10 
11   //error method name_= is defined twice
12   /*def name_=(name:String) {
13       this.name=name;
14     }*/
15 
16 }
17 
18 class Student2 {
19   //没有修饰符的val变量,在编译时会被声明为private类型,但只提供公共的get方法
20   val name = "tele";
21 
22 }
23 
24 class Student3 {
25   //使用private修饰的var变量.只有私有的get与set,如需访问,需要自定义get与set
26   private var name = "tele";
27 
28   def getName = name;
29 
30   def setName(name: String) {
31     this.name = name;
32   }
33 
34 }
35 
36 class Student4 {
37   //使用private[this]修饰的var变量,为对象所私有,同一个类的不同对象不能相互访问该属性,也就是对象隔离级别
38   private[this] var name = "tele";
39 
40   //error,虽然s也是Student4类型,但是无法在Student4类中获取s的name,当然,如果提供了自定义的get方法则可以访问到
41   /*def getOtherName(s:Student4) {
42      println(s.name);
43    }*/
44 
45 }
46 
47 //生成java风格的get与set -> getName() setName(),当然还有name,name_=
48 class Student5 {
49   //使用占位符时必须声明参数类型
50   @BeanProperty var name: String = _;
51 }
52 
53 //同上,参数在主构造器中
54 class Student6(@BeanProperty var age: Int)
55 
56 object Student {
57 
58   def main(args: Array[String]): Unit = {
59 
60     // Student
61     val s1 = new Student();
62     println(s1.name);
63     //只能赋值为String类型,因为在Student中name别声明为String
64     s1.name = "yeye";
65     println(s1.name);
66 
67     //Student2
68     /* val s2 = new Student2();
69       println(s2.name);
70      //error
71      //  s2.name="yeey";*/
72 
73     //Student3
74     /* val s3 = new Student3();
75      println(s3.getName);
76 
77      s3.setName("yeye");
78      println(s3.getName);*/
79 
80     //Student5
81     /*val s5 = new Student5();
82     s5.setName("yyyy");
83     println(s5.getName);     */
84 
85     //Student6
86     val s6 = new Student6(15);
87     println(s6.getAge());
88 
89   }
90 }

猜你喜欢

转载自www.cnblogs.com/tele-share/p/10039300.html