1

为什么我的子类方法没有覆盖其父类中相同签名的方法?

概括:

我有一个PlayerPaddle扩展抽象类的类Paddle,它扩展了抽象类 Actor(这里的上下文是乒乓球游戏)。Paddle并且PlayerPaddle两者都有一个具有相同签名的方法:

public void moveDown()

目的是让PlayerPaddle moveDown方法覆盖Paddle. 这里的问题是当我调用this.moveDown()inside时PlayerPaddle,只调用了moveDown方法Paddle

细节:

moveDown()在in上设置的断点Paddle被触发,而在moveDown()in上设置的断点PlayerPaddle从不触发。我也尝试@Override了该PlayerPaddle moveDown方法,但它仍然调用该Paddle moveDown方法。

上下文:

目标是让对象以与其他对象PlayerPaddle不同的速度向上/向下移动。Paddle因此,该moveUp方法也会出现同样的问题。

下面的代码:

abstract public class Actor {
    public void releasedEvent(KeyEvent e) {
    }
}

abstract public class Paddle extends Actor {
     public void moveDown() { // this method is called
          body.setVel(0, Game.dX / 10.);   
     }
}


public class PlayerPaddle extends Paddle {
    @Override
    public void moveDown() { // this method never gets called
       body.setVel(0,  Game.dX );
    } 

    public void receiveEvent(KeyEvent e) {
       if (e.getKeyCode() == KeyEvent.VK_UP) {
          this.moveUp(); 
       } else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
          this.moveDown(); // Want to call moveDown() inside PlayerPaddle
       }
    }

}

我很高兴提供澄清。

4

1 回答 1

4

看简单的案例,它的工作原理:

public class Test{

  public static void main(String args[])
  {     
    new PlayerPaddle().receiveEvent();
  }
}
abstract class Actor {
  public void releasedEvent(KeyEvent e) {
  }
}
abstract class Paddle extends Actor {
  public void moveDown() { // this method is called
      System.out.println("paddle");
  }
}
class PlayerPaddle extends Paddle {
  @Override
  public void moveDown() { // this method never gets called
   System.out.println("playerpaddle");
  } 
  public void receiveEvent() {
     this.moveDown(); // Want to call moveDown() inside PlayerPaddle      
  }
}

它调用 PlayerPaddle 之一。

于 2013-05-10T04:33:07.673 回答