카테고리 없음

Kotlin the difference of nested class and inner class (Explanation with Code examples)

slowbooktech 2022. 5. 29. 00:53

Difference

l Explanation

While nested class can not approach to the outer class's properties, inner class is able to approach them.

 

l Code

l explanation

'unresolved reference' has been occurred since the value named 'topic'  is defined in outer class 'Seoul'. This value can not be used inside of the nested class 'Hongdae'.

 


1. nested class

we call the class (which is in the other class ) nested class.

Since Hongdae is a region inside of the Seoul city, I made the seoul class as the outer class, hongdae as the nested class. The code under this paragraph is printing the properties of Hongdae class using method 'printTourPlace'. But this method, which is oriented from the nested class 'Hongdae', can not use the value of 'topic', which is oriented from the outer class 'Seoul'.

fun main() {
    println(Seoul.Hongdae().tourPlace)
    var specificAddress = Seoul.Hongdae()
    specificAddress.printTourPlace()
}
   //practicing the nested class
class Seoul {
       private var topic : String = "photo spot"
       class Hongdae{
           var tourPlace:String ="tourplace is hongdae"
           private var address = 101
           fun printTourPlace(){
               println("I recommend you to go ${address} street. Your ${tourPlace}")
           }
       }
   }

l code result


2. Inner class

To use inner class, you can just add the word 'inner' in front of the nested class. Then, you should regard the outer class as the one seperated class from the inner class. I mean, you should add () before referencing the inner class.

fun main() {
    println(Seoul().Hongdae().tourPlace)
    var specificAddress = Seoul().Hongdae()
    specificAddress.printTourPlace()
}
   //practicing the inner class
class Seoul {
       private var topic : String = "photo spot"
       inner class Hongdae{
           var tourPlace:String ="tourplace is hongdae"
           private var address = 101
           fun printTourPlace(){
               println("I recommend you to go ${address} street for ${topic}")
           }
       }
   }

l the result of the code