(一)内部类的基本使用
定义格式: class 类 { class 内部类 }
使用格式: new 类的实例.内部类()
// 外部类
class Car() {
var wheel: Int = 3
def run(): Unit = {
println("run....")
}
// 内部类
class Engin() {
val power: Int = 12
}
}
def main(args: Array [String ]): Unit = {
val c1 = new Car();
val eng =new c1.Engin()
println(eng.power)
}
内部类
- 格式:在一个类的里面,再写一个类
- 作用:组织逻辑更加严谨,避免命名的冲突
//外部类
class Car() {
var wheel: Int = 3
// 私有成员
private var speed: Int = 0
def run(): Unit ={
println(s"速度为:${speed},run....")
}
// 内部类
class Engin() {
def acc(increment: Int): Unit ={
speed += increment
}
}
class AutoPark(){}
}
def main(args: Array[String]): Unit ={
val c1 = new Car();
// c1.speed // 私有成员不能访问
c1.run()
val en = new c1.Engin()
en.acc(10)
c1.run()
}