加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 通过一组构造函数传递参数的问题

发布时间:2020-12-16 09:52:31 所属栏目:安全 来源:网络整理
导读:我的问题是 scala继承细节.我有以下代码. package scalasandboxobject Main { def main(args: Array[String]): Unit = { val creature: Creature = new Human("First") creature.rename("Second") creature.introduce }}class Creature(var name: String) {
我的问题是 scala继承细节.我有以下代码.

package scalasandbox

object Main {
  def main(args: Array[String]): Unit = {
    val creature: Creature = new Human("First")
    creature.rename("Second")
    creature.introduce
  }
}

class Creature(var name: String) {
  def introduce = println("I'm creature: " + name)

  def rename(newName: String) = {
    println("Creature was renamed to: " + newName)
    name = newName
  }
}

class Human(name: String) extends Creature(name) {
  override def introduce = println("I'm Human: " + name)
}

产生以下输出

Creature was renamed to: Second
I'm human: First

我希望它是“我是人类:第二”,因为重命名方法应该改变字段值.我用反编译器打开了Human类:

package scalasandbox;

import scala.Predef.;
import scala.ScalaObject;
import scala.collection.mutable.StringBuilder;
import scala.reflect.ScalaSignature;

@ScalaSignature(bytes="0601212A!01020113t)01*^7b]*t1!0107tG06d27m]1oIn|07p01012407011!020502b215t!!0302n05tA1I]3biV24Xr0502f355tABC01160325318-317b23tyABA06TG06d27m242kK16$b02Ct01050305132102n02t9fW.32t03'Yq!a0313n05Ua21A02)sK22,g-0302301t111336:j]36T!!0607t13i01A21A1602rqJg.33;?)taR040502b01!)21#07a01%!)q0401C!A05I21N34;s_22,8-Z1302CA211BI0503G121A!268ji02")
public class Human extends Creature
  implements ScalaObject
{
  private final String name;

  public void introduce()
  {
    Predef..MODULE$.println(new StringBuilder().append("I'm Human: ").append(this.name).toString());
  }

  public Human(String name)
  {
    super(name);
  }
}

并看到“私有最终字符串名称;”那里.我认为它隐藏了生物名称字段.和

Predef..MODULE$.println(new StringBuilder().append("I'm Human: ").append(this.name).toString());

由于“this.name”而不是方法调用“this.name()”,这些东西看起来也很可疑.任何人都可以解释我的错误在哪里以及实现这两个类的正确方法是什么?

解决方法

您在Human类中使用的name变量解析为Human的构造函数参数,Scala将自动为构造函数外部使用的构造函数参数创建私有val.在你的情况下这是不幸的.你可以阻止这个,例如通过在Human中以不同方式命名您的参数,例如纳米:

class Human(nm: String) extends Creature(nm)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读