内部类:定义在类里面的类(内部类可以访问私有成员用它来操作类的私有成员,封闭性更好)
Scala
class Student{
var age=18
def say():Unit={
}
class Book{
val bookName: Any = "Scala程序设计"
}
}
object Test19 {
def main(args: Array[String]): Unit = {
val s1=new Student()
val book1=new s1.Book()
println(book1.bookName)
}
}
输出:Scala程序设计
Scala
class Car2 {
private var speed=100
val color="red"
//
class Engin(var maxSpeed:Int){
def acc():Unit={
speed+=10
if (speed>maxSpeed){
speed=maxSpeed
}
println("speed",speed)
}
def sub():Unit={
speed-=10
}
}
override def toString: String = {
s"当前的速度是${speed}"
}
}
object Test19_1{
def main(args: Array[String]): Unit = {
val c=new Car2()
var engin=new c.Engin(maxSpeed=120)
engin.acc()
engin.acc()
engin.acc()
println(c)
engin.sub()
println(c)
}
}
输出:(speed,110)
(speed,120)
(speed,120)
当前的速度是120
当前的速度是110