Scala编程

Scala编程详解10:面向对象编程之类

2020-05-26  本文已影响0人  勇于自信

大纲
1、定义一个简单的类
2、field的getter与setter详解
3、constructor详解
4、内部类介绍

1. 定义一个简单的类
object scala_demo07 {
  def main(args: Array[String]): Unit = {
    // 创建类的对象,并调用其方法
    val helloWorld = new HelloWorld
    helloWorld.sayHello()
    print(helloWorld.getName) // 也可以不加括号,如果定义方法时不带括号,则调用方法时也不能带括号

  }
}

// 定义类,包含field以及方法
class HelloWorld {
  private var name = "leo"
  def sayHello() {
    print("Hello, " + name)
  }
  def getName = name
}
2. getter与setter
3. 自定义getter与setter

object scala_demo07 {
  def main(args: Array[String]): Unit = {
    val leo = new Student
    print(leo.name)
    leo.name = "leo1"
  }
}

class Student {
  private var myName = "leo"
  def name = "your name is " + myName
  def name_=(newValue: String)  {
    print("you cannot edit your name!!!")
  }
}

输出
your name is leoyou cannot edit your name!!!

4. 仅暴露field的getter方法
class Student {
  private var myName = "leo"

  def updateName(newName: String) { 
    if(newName == "leo1") myName = newName 
    else print("not accept this new name!!!")
  }

  def name = "your name is " + myName
}
5. private[this]的使用
class Student {
  private var myAge = 0
  def age_=(newValue: Int) { 
    if (newValue > 0) myAge = newValue 
    else print("illegal age!") 
  }
  def age = myAge
  def older(s: Student) = {
    myAge > s.myAge
  }
}
6. Java风格的getter和setter方法
7. 辅助constructor
class Student {
  private var name = ""
  private var age = 0
  def this(name: String) {
    this()
    this.name = name
  }
  def this(name: String, age: Int) {
    this(name)
    this.age = age
  }
}
8. 主constructor
9. 内部类
import scala.collection.mutable.ArrayBuffer
class Class {
  class Student(val name: String) {}
  val students = new ArrayBuffer[Student]
  def getStudent(name: String) =  {
    new Student(name)
  }
}

val c1 = new Class
val s1 = c1.getStudent("leo")
c1.students += s1

val c2 = new Class
val s2 = c2.getStudent("leo")
c1.students += s2
上一篇下一篇

猜你喜欢

热点阅读