Override a class variable from parent classes function

只谈情不闲聊 提交于 2020-06-17 12:57:40

问题


I have a parent and child class.

class a {
val name :String = "jo"
 def extract(){
  println(name)
 }
}

now i need to do as below.

class b extends a {
 override def extract(){
  override var name :String = "dave". //the problem is here and
  super.extract()
  name = "jenny" //here
  super.extract()
 }
}

Issues Im facing now.

1) I cannot use var if im to override the value in class a, needs to be immutable to use override.

2) needs to call the super function twice with different variable.

3) Cannot call override inside the function

Would really appreciate if anyone knew how to get around this. I cannot change anything in class a. I can work only on b and needs to call the extract function twice with different values for the variable.


回答1:


It's not possible to override super class immutable values inside method.

Instead you can change var in super class but don't override in child class.

Please check below code.

scala> :paste
// Entering paste mode (ctrl-D to finish)

class a {
 var name = ""
 def extract(){
  println(name)
 }
}


class b extends a {
 override def extract(){
  name = "dave" //the problem is here and
  super.extract()
  name = "jenny" //here
  super.extract()
 }
}

// Exiting paste mode, now interpreting.

defined class a
defined class b

scala> (new b).extract
dave
jenny

If you want to call extract method twice with different name values, Just extend parent class & override name, create child object with different name values like below.

scala> :paste
// Entering paste mode (ctrl-D to finish)

class a {
 val name = ""
 def extract(){
  println(name)
 }
}


class b (override val name: String) extends a {
 override def extract(){
  super.extract()
 }
}

// Exiting paste mode, now interpreting.

defined class a
defined class b

scala> (new b("dave")).extract
dave

scala> (new b("jenny")).extract
jenny

scala>


来源:https://stackoverflow.com/questions/61852375/override-a-class-variable-from-parent-classes-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!