0

Currently I am shifting some code from java to kotlin and I came across a problem that is Nested classes can not be initialized through derived class of Out class while Java Allow so. The code Elaborate it well

/// Java Outer Class
public class JavaOuterClass {


static class InnerClass{

    }

}
/// Java derived Class
public class JavaDerivedClass extends JavaOuterClass {
}
///Java Class Initialization in main method
public class JavaTest {

public static void main(String[] args) {
   JavaOuterClass.InnerClass instance = new JavaOuterClass.InnerClass();
//inner class is allowed to instantiate through outer class 
   JavaDerivedClass.InnerClass instance1 = new JavaDerivedClass.InnerClass();
   }
}

I can Initialize the nested class through derived class.While in kotlin

//Kotlin outer class
open class KotlinOutClass(){
lateinit var name:String;

init {
    this.name = "outerClass"
}

class InnerClass() {

    fun InnerClassMethod() {
        print("InnerClass method")
    }

  }
}

//Kotlin derived class



class KotlinDerivedClass(): KotlinOutClass() {

fun subClassMethod(){
    print("subClassMethod")
  }
}

Now I can not initialize the nested class in parent class through derived class class of outer class

 ///kotlin Class Initialization in main method
class KotlinTestClass {

fun main(args: Array<String>) {
   var instance: KotlinOutClass.InnerClass = KotlinOutClass.InnerClass();
   var instance1: KotlinDerivedClass.InnerClass = KotlinDerivedClass.InnerClass();
  }

}

enter image description here

java is allowing this behavior but doing same is no allowed in kotline. could any one let me know why is not possible in kotlin, if it is how?

GhostCat
  • 137,827
  • 25
  • 176
  • 248
Irfan Ul Haq
  • 1,065
  • 1
  • 11
  • 19
  • 2
    Please read [no pictures of exceptions](http://idownvotedbecau.se/imageofanexception/) / [no pictures of code](http://idownvotedbecau.se/imageofcode). Then use the [edit] link to replace screen shots of text with nicely formatted/indented text within your question. – GhostCat Oct 10 '19 at 07:47
  • @GhostCae The code is already provided but just want to more elaborate how it looks in the IDE – Irfan Ul Haq Oct 10 '19 at 08:01

0 Answers0