Scala | 内部类

24 阅读1分钟

内部类

1.内部类的定义

  • 定义在类或者对象内部的类称为内部类。
  • 在类的内部有:属性,方法,类。

2.内部类的基本使用

定义格式: class 类 {  class 内部类 }

使用格式: new 类的实例.内部类()

3.实例化内部类的对象

  • val 外部类的对象 = new 外部类();
  • val 内部类的对象 = new 外部类的对象.内部类()
// 外部类
class Class1() {

  // 写在C1内部的类
  class Class2() {
    def test():Unit = {
      println("test....")
    }
  }
}

def main(args: Array[String]): Unit = {
  val c1 = new Class1()
  val c2 = new c1.Class2()
  c2.test()
}

4.作用

  • (1) 整理代码
  • (2) 访问 操作 外部类的私有成员
// 外部类
class Car() {
  // 私有属性:在类的外部帮你访问
  private var speed:Int = 0

  def getSpeed():Unit = {
    println(s"当前速度是${speed}")
  }

  class Engin() {
    def accSpeed(s:Int = 10):Unit = {
      speed += s
    }
    def subSpeed(s:Int = 10):Unit = {
      speed -= s
    }
  }
}
def main(args: Array[String]): Unit = {
  val car = new Car();
  val engin = new car.Engin()
  engin.accSpeed(20)
  engin.subSpeed(10)
  car.getSpeed
}

5.内部对象

内部对象:  在class 的内部 定义object对象

  • new Class的实例
  • 实例.对象
class Class1() {

  object obj {
    var age:Int = 10
    def say():Unit = {
      println(s"hello, ${age}")
    }
  }

}

def main(args: Array[String]): Unit = {
  val c1 = new Class1()
  c1.obj.say()
}