scala的内部类

50 阅读1分钟

内部类的基本使用

实例化内部类的对象

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

object class18 {

  // 外部类
  class Class1() {

    // 写在c1内部的类
    class Class2() {
      def test(): Unit = {
        println("test...")
      }
    }
  }
  def main(args: Array[String]): Unit = {
  // 使用格式
  // val 外部类的对象 = new 外部类()
  // val 内部类的对象 = new 外部类的对象.内部类()
    val c1 = new Class1()
    val c2 = new c1.Class2()
    c2.test()
  }
}

内部类的作用

1.整理代码
2.访问 操作 外部类的私有成员

案例

object class19 {
  // 外部类
  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()
  }
}

屏幕截图 2025-11-17 091937.png

内部对象

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

定义格式: class 类名 {  object 对象名{ 属性;方法() }}

使用格式:类名.对象名.属性名; 类名.对象名.方法名()

object class20 {

  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()
  }
}