在java中扩展抽象类

时间:2015-10-26 23:50:04

标签: java inheritance abstract-class subclass superclass

我有两个班级,比如汽车和卡车,它们是抽象级车辆的子类。我有一段代码在卡车和汽车之间是常见的,所以为了节省代码空间我想把方法放到超类中,我可以在子类中调用它。我遇到了麻烦。这是我得到的代码。

public class TruckShape extends VehicleShape    //The code here is the same for both classes
{
   public TruckShape(int x, int y, int width)
   {
      this.x = x;
      this.y = y;
      this.width = width;
   }
   .
   .
   .
   public void translate(int dx, int dy)
   {
      x += dx;
      y += dy;
   }
}

此代码存在于Truck和Car类中。出于某种原因,每当我尝试将它放入超级类时,它就会编译,但是当我拖动汽车(用鼠标)来翻译它时,它根本不会移动。这就是我得到的:

import java.awt.Graphics2D;

public abstract class VehicleShape implements SceneShape
{  
   .
   .
   .

   public void translate(int dx, int dy)
   {
      x += dx;
      y += dy;
   }

   private boolean selected;
   private int x;
   private int y;
}

当我将translate方法放入抽象超类并将其从子类中删除时,程序无法正常工作。我尝试创建一个超类构造函数并在那里初始化x和y而不是在子类中查看是否可能是为什么翻译不起作用,但这没有做任何事情。有没有办法让我得到一个在抽象超类中工作的2个子类之间共享的方法?这样,程序工作,没有重复的代码。感谢。

0 个答案:

没有答案