从 java 了解类的情况下, 了解 Scala 的类并不难. Scala 类中的字段自动带 getter 和 setter 方法, 用 BeanProperty 注解生成 javaBean 对象的 getXXX 与 setXXX 方法
构造 Scala 的类
- class Counter {
- // 初始化字段值 value
- private var value = 0
- // 方法默认是 public 的
- def increment() {
- value +=1
- }
- def current() = value
- }
Scala 中类不必声明为 public,Scala 源文件可以包含多个类, 这些类都是默认 public 的.
- // 构造对象调用 Counter
- val counter = new Counter()
- // 一般习惯对改值器使用 (), 对取值器不适用 ()
- counter.increment()
- println(counter.current)
构造类 setXXX 与 getXXX
- public class Person {
- private int age;
- public int getAge() {return age}
- public void setAge(int age) {this.age =age}
- // 在 java 中使用 set,get 方法对属性进行修改获取是比较好的一种方式. Scala 中每个字段默认提供 getter 和 setter 方法
- // get 方法
- def age = privateAge
- // set 方法
- def age(newValue: Int): Unit = {
- if (newValue> privateAge) {
- privateAge = newValue
- }
- }
- // junit 的测试
- Test
- def testCounter(): Unit = {
- val counter = new Counter()
- counter.increment()
- println(counter.current())
- counter.age(10)
- println(counter.age)
- // 类私有的自动无法创建对象. 属性调用
- }
- // Scala 的字段加 BeanProperty
- import scala.reflect.BeanProperty
- class Person {
- BeanProperty
- // 默认会生成 get/set 方法
- var name:String =
- }
构造器
定义以 this 开头的是辅助构造器
- /**
- * 辅助构造器
- *
- * param username
- */
- def this(username: String) {
- this()
- this.username = username
- }
- /**
- * 辅助构造器
- * param username
- * param score
- */
- def this(username: String, score: Int) {
- // 调用上一个构造器
- this(name)
- this.score = score
- }
- // 3 种方法构建对象
- val p1 = new Person
- val p2 = new Person("Bob")
- val p3 = new Person("Bob",24)
- // 构建主构造器
- class Person(val name:String="",val age:Int=10) {
- println("这是构造方法")
- def des = "name="+name+",age="+age
- }
val pserson = new Person("haha",12) 将会执行主构造方法
内部类
和 java 类似, Scala 中也有内部类, 但是比 java 更丰富些, Scala 中调用的方式是 new OuterClass.innerClass 而 java 中式 outClass.new InnerClass()
- class NetWork {
- class Member(val name: String) {
- val contacts = new ArrayBuffer[Member]
- }
- private val members = new ArrayBuffer[Member]
- def join(name: String) = {
- val m = new Member(name)
- members+=m
- m
- }
- }
- val beijing = new network
- val xian = new network
- val s1 = beijing.join("Bob")
- val s2 = beijing.join("Michael")
- // 同一种类型可以同一个集合
- s1.conttacts +=s2
- val s3 = xian.join("Alice")
- // 不可以将 s3 添加到 s1 中, 因为不是同一个 Network 对象
来源: https://www.cnblogs.com/codegeekgao/p/9619030.html