内部类
- 实例化内部类的对象?
val 外部类的对象 = new 外部类();
val 内部类的对象 = new 外部类的对象.内部类()
package level02
// 内部类
// 1. 实例化内部类的对象?
// val 外部类的对象 = new 外部类();
// val 内部类的对象 = new 外部类的对象.内部类()
object l11 {
//外部类
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()
}
}
package level02
// 内部类
// 1. 实例化内部类的对象?
// val 外部类的对象 = new 外部类();
// val 内部类的对象 = new 外部类的对象.内部类()
/**
*2.作用
*(1)整理代码
*(2)访问,操作 外部类的私有成员
*
*/
object l12 {
//外部类
class Car() {
//私有属性,在类的外部不能访问
private var speed:Int=0
def getSpeed():Unit={
println(s"当前速度是${speed}")
}
class Engin() {
def accsSpeed(s:Int=10):Unit={
speed+=s
}
def subSbeed(s:Int=10):Unit={
speed-=s
}
}
}
def main(args: Array[String]): Unit = {
val car=new Car;
val engin=new car.Engin()
engin.accsSpeed(20)
engin.subSbeed(10)
car.getSpeed()
}
}
内部对象:在class的内部,定义object对象
1.new Class的实例
2.实例.对象
package level02
/*
*内部对象:在class的内部,定义object对象
* 1.new Class的实例
* 2.实例.对象
*
*/
object l13 {
class Clacc1() {
object obj {
var age:Int=10
def say():Unit={
println(s"hello,${age}")
}
}
}
def main(args: Array[String]): Unit = {
val c1=new Clacc1()
c1.obj.say()
}
}