繁体   English   中英

关于在scala中调用超类方法的困惑

[英]a confusion about calling super class method in scala

这是我的Scala代码,我先粘贴它

abstract class Item {
  def price(): Double
  def descript(): String
} 

class SimpleItem(var price: Double, var descript: String) extends Item

class Bundle(price: Double, descript: String, var other: Item) 
  extends SimpleItem(price, descript) {

  override def price = other.price + super.price
  override def descript = "this item can contain other item,and now it's containning:"+
    other.descript
}

Bundle方法价格中,当我使用super.price ,编译器认为我使用超类的私有属性,但当我将其更改为super.price() ,编译器认为我将()添加到Double 现在我很困惑:还有另一种方法可以调用超类的方法吗?

可悲的事实是scala不允许你覆盖getter和var的setter。 这与统一访问原则冲突(与val s形成对比,你可以覆盖),但你必须忍受这种限制。

一个(有点难看)的工作是自己定义一个getter和setter,如下所示:

class SimpleItem(private var _price: Double, private var _descript: String) extends Item{
  def price = _price
  def price_=( value: Double ) { _price = value }
  def descript = _descript
  def descript_=( value: String ) { _descript = value }
}

SimpleItem仍然在功能上等同于你的SimpleItem版本,你现在可以覆盖setter和getters(现在你的Bundle类将按原样编译)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM