scala 类

56 阅读1分钟
//内部类
//1.实例化内部类的对象?
//  val 外部类的对象 = new 外部类()
//  vsl 内部类的对象 = new 外部类的对象.内部类()

   // 外部类
class Class01() {
  // 内部类(属于Class01的实例成员)
  class Class02() {
    def test(): Unit = {
      println("test...")
    }
  }
}

// 程序入口对象
object Main {
  def main(args: Array[String]): Unit = {
    val c1 = new Class01()       // 1. 先创建外部类对象
    val c2 = new c1.Class02()    // 2. 通过外部类对象c1实例化内部类(关键修正)
    c2.test()                    // 调用方法,输出:test...
  }
}
object Main {
  // 外部类 Car(定义在 Main 对象内部)
  class Car() {
    // 私有属性,仅内部可访问
    private var speed: Int = 0

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

    // 内部类 Engin
    class Engin() {
      def accSpeed(s: Int = 10): Unit = {
        speed += s  // 内部类可访问外部类的私有属性
      }
    }

    // subSpeed 是 Car 类的方法,放在 Car 类的大括号内
    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)
    car.subSpeed(10)  // subSpeed 是 Car 的方法,需用 car 调用
    car.getSpeed()  // 输出:当前速度是10
  }
}
object Main {
  // 外部类 Class1
  class Class1() {
    // 内部单例对象 obj
    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()  // 调用内部对象的方法,输出:hello,10
  }
}