📜  Kotlin嵌套类和内部类

📅  最后修改于: 2021-01-05 07:57:03             🧑  作者: Mango

Kotlin嵌套班和内部班

Kotlin嵌套课程

嵌套类是在另一个类内部创建的类。在Kotlin中,嵌套类默认情况下是static ,因此无需创建类的对象即可访问其数据成员和成员函数。嵌套类无法访问外部类的数据成员。

class outerClass{
   //outer class code
    class nestedClass{
      //nested class code
    }
}

Kotlin嵌套类示例

class outerClass{
    private var name: String = "Ashu"
    class nestedClass{
var description: String = "code inside nested class"
        private var id: Int = 101
        fun foo(){
          //  print("name is ${name}") // cannot access the outer class member
println("Id is ${id}")
        }
    }
}
fun main(args: Array){
// nested class must be initialize
println(outerClass.nestedClass().description) // accessing property
var obj = outerClass.nestedClass() // object creation
    obj.foo() // access member function
}

输出:

code inside nested class
Id is 101

科特林内层阶级

内部类是在另一个类中使用关键字inner创建的类。换句话说,我们可以说标记为“内部”的嵌套类称为内部类。

内部类不能在接口内部或非内部嵌套类中声明。

class outerClass{
   //outer class code
    inner class innerClass{
      //nested class code
    }
}

内部类优于嵌套类的优点是,即使它是私有的,它也能够访问外部类的成员。内部类保留对外部类对象的引用。

科特林内部阶级的例子

class outerClass{
     private  var name: String = "Ashu"
     inner class  innerClass{
var description: String = "code inside inner class"
        private var id: Int = 101
       fun foo(){
println("name is ${name}") // access the outer class member even private
println("Id is ${id}")
        }
    }
}
fun main(args: Array){
println(outerClass().innerClass().description) // accessing property
var obj = outerClass().innerClass() // object creation
    obj.foo() // access member function

}

输出:

code inside inner class
name is Ashu
Id is 101