Home > database >  How to get new variable value from inherited class?
How to get new variable value from inherited class?

Time:02-15

open class Parent(){
  protected var z : Int? = null

  private fun getMyAge(){
    val x = 65
    val y = 10
    z = x % y 
  }
}

class Child:Parent(){
 ovveride fun getMyAge()
  println(z)  //here I get null
}

My question is: why I get null? Am I getting a variable from an inherited class incorrectly?

CodePudding user response:

It's because when you override the function, the super function is not called. If you want the function in parent class called, you must change your code to this:

open class Parent(){
  protected var z : Int? = null

  private fun getMyAge(){
    val x = 65
    val y = 10
    z = x % y 
  }
}

class Child:Parent(){
 ovveride fun getMyAge()
  super.getMyAge()
  println(z)
}
  • Related