内部类

32 阅读1分钟

一. 内部类的定义

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

二. 内部类的基本使用

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

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

package level02

// 内部类
//1.实例化内部类的对象?
//  val 外部类的对象 = new 外部类()
//  val 内部类的对象 = new 外部类的对象,内部类()

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

三. 内部类的综合案例

(1)在Car类中,再次定义Engine类

package level02

// 内部类
//1.实例化内部类的对象?
//  val 外部类的对象 = new 外部类()
//  val 内部类的对象 = new 外部类的对象,内部类()
/*
* 2.作用
*   (1) 整理代码
*   (2) 访问,操作 外部类的私有成员
*
* */
object class18 {
  //  外部类
  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()
  }
}

(2)内部类的好处

1.逻辑组织:引擎与 汽车紧密相关,它们都属于汽车的上下文。将它们作为内部类可以使代码更为整洁和逻辑清晰。
2.简化访问:内部类能够方便地访问外部类的私有成员,这样引擎类可以操作汽车的速度而不需要通过外部接口。
3.减少命名冲突:由于内部类的作用范围限制在外部类内,避免了名称冲突(在大型项目中,可能会有多个引擎类)。

四. 内部对象

内对象,就是定义在class内部的object。

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

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

package level02
/*
* 内部对象 :在class 的内部,定义object对象
*  1.new Class的实例
*  2.实例,对象
* */
object class19 {
  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()

  }
}