【问题标题】:Subclass method code being ignored when calling super method within调用超方法时忽略子类方法代码
【发布时间】:2015-03-07 14:00:09
【问题描述】:

我正在创建一个基于文本输入的程序。 每次收到输入时,都会有基于文本的(系统打印)输出和使用 JFrame 的图形表示输出。

我有一个扩展UiPlayer 的类Player

UiPlayer 中的方法控制玩家在 UI 2D 地图周围。 Player 中的方法更改变量以显示基于文本的输出。 Player中的相关代码:

public class Player extends UiPlayer
{
  private MyDirection facing;

  public Player(.....)   //irrelevant arguments
  {
    super(.....);
    facing = MyDirection.EAST;
  }


  /**
  *  make the player turn right, both in text and in GUI window
  */
  public void turnRight()
  {
    super.turnRight();
    if(facing == MyDirection.NORTH)
    {facing = MyDirection.EAST;} 
    else if(facing == MyDirection.WEST)
    {facing = MyDirection.NORTH;}
    else if(facing == MyDirection.SOUTH)
    {facing = MyDirection.WEST;}
    else
    {facing = MyDirection.SOUTH;}
  }

  /**
  * make the player turn 180 degrees, both in text and on graphics window
  */
  public void turnAround()
  {
    super.turnAround();
    if(facing == MyDirection.NORTH)
    {facing = MyDirection.SOUTH;}
    else if(facing == MyDirection.WEST)
    {facing = MyDirection.EAST;}
    else if(facing == MyDirection.SOUTH)
    {facing = MyDirection.NORTH;}
    else
    {facing = MyDirection.WEST;}
}

然而,由于某种原因,虽然turnRight()turnLeft()工作得很好,但是当turnAround()被调用时,如果它包括调用其中的超级方法,则调用超级方法,玩家打开GUI和所有其他更改基于文本的方向的代码(即facing)似乎被忽略了。

如果我不包含 super 方法,facing 的值每次都会变化,完美。

我尝试重命名方法,并在 if 语句后放置 super.turnAround()

编辑:另外,我无法访问 UiPlayer 的代码,我只有方法文档。它指出|无效 |转身() |将播放器转过来,使其朝向相反的方向。

有什么想法吗? >

【问题讨论】:

  • 你能添加super-Method吗?
  • 我猜 super.turnAround() 和 Player.turnAround() 做同样的事情,结果是玩家转身两次,最终面朝同一个方向。
  • UiPlayer 类在哪里定义 turnAround 方法?
  • 我无权访问超级方法的代码,只有它使播放器转向相反方向的文档。 ://

标签: java inheritance methods


【解决方案1】:

如果我是你,并且你无法让 turnAround 工作,并且你无权修复代码和类并查看到底发生了什么,

然后我会调用 两次 turnLeftturnRight,如果你考虑一下,这基本上是 turnAround..

这不是处理它或其他什么的超级优化方式,但它应该可以解决你的问题:)

【讨论】:

    猜你喜欢
    • 2011-10-24
    • 1970-01-01
    • 2018-01-22
    • 1970-01-01
    • 1970-01-01
    • 2012-04-18
    • 1970-01-01
    相关资源
    最近更新 更多