内部类

0 阅读1分钟

内部类

1.实例华内部的对象?

val 外部类的对象 = new 外部类()

val 内部类的对象 = 外部类的对象.new 内部类()

eg1:

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

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

new Class的实测对象

实例.对象

eg2:

object class02 {
  //外部类
  class Car {
    //私有属性,在类的外部不能访问
    private var speed = 0//speed += s,speed -= s

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

    class Engin() {
      def accSpeed(s:Int = 10):Unit = {
        speed += s
      }
      def subhSpeed(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.subhSpeed(10)
    car.getClass()

  }
}