22内部类

28 阅读1分钟

(一)内部类的定义

定义在类或者对象内部的类称为内部类。

在类的内部有:属性,方法,类。

image.png

package level02

object Class17{
    class C1 {
      class B1 {
        def say(): Unit = {
          println("B1.....")
        }
      }
    }

    def main(args: Array[String]): Unit = {
      // 1. 创建一个C1的对象
      val c1 = new C1()
      // 2. 创建一个B1的对象
      val b1 = new c1.B1()
      b1.say()
    }
}

image.png

(二)内部类的基本使用

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

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

在Car类中,再次定义Engine

package level02
/*
内部类:在类的内部,写另一个类
* 作用:整理代码,访问私有成员
* */
object Class18 {

    class C1 {
      // 私有成员,不能在类的外部修改
      private var score: Int = 85

      class B1 {
        def addScore(s: Int): Unit = {
          score += s
        }
        def say(): Unit = {
          println(s"B1...$score")
        }
      }
    }

    def main(args: Array[String]): Unit = {
      // 1. 创建一个C1的对象
      val c1 = new C1()
      // 2. 创建一个B1的对象
      val b1 = new c1.B1()
      b1.addScore(10)
      b1.say()
    }

}