0

I have a (more complex) version of these 4 classes the problem is when I try to initialize Test() android studio tells me cannot call data.log() on a null object reference. Why is this? how can i fix it?

abstract class Test() {
    protected abstract val data: CustomClass
    init {
        data.log()
    }
}
class myClass(): Test() {
    override val data = Hello()
}
abstract class CustomClass() {
    function log() {
        Log.i("TEST", "HELLO");
    }
}
class Hello(): CustomClass() {
    
}

I have a lot of classes that extend Test() and Hello() I do not want to have to call data.log() in multiple classes to avoid repeating code

glend
  • 1,592
  • 1
  • 17
  • 36

1 Answers1

0

Try to evaluate your code step by step:

  1. invoke myClass() -> myClass constructor called from your code
  2. invoke Test() -> parent constructor called from myClass constructor
  3. invoke Test's init -> init section called from Test constructor
  4. NPE -> data field is not initialized yet

As you can see, the init section is called BEFORE the data is initialized. Solution to your problem is pretty simple, move the data field right into the Test's constructor and remove the abstract modifier:

abstract class Test(protected val data: CustomClass) {
    init {
        data.log()
    }
}

class myClass(): Test(Hello())

P.S.: I hope this is just an example and you don't start your class names with lowercase. :)

kejm
  • 103
  • 1
  • 6