不确定如何在两个类之间使用实现

时间:2012-11-08 21:44:54

标签: java interface implementation

这是我的班级,所有事情都在:

import java.awt.Color;
import java.awt.Graphics;

//This class will not compile until all 
//abstract Locatable methods have been implemented
public class Block implements Locatable
{
    //instance variables
    private int xPos;
    private int yPos;
    private int width;
    private int height;
    private Color color;

    //constructors
    public Block () {}

    public Block(int x,int y,int w,int h)
    {
        xPos = x;
        yPos = y;
        width = w;
        height = h;
    }

    public Block(int x,int y,int w,int h, Color c)
    {
        xPos = x;
        yPos = y;
        width = w;
        height = h;
        color = c;
    }

    //set methods
    public void setBlock(int x, int y, int w, int h)
    {
        xPos = x;
        yPos = y;
        width = w;
        height = h;
    }

    public void setBlock(int x, int y, int w, int h, Color c)
    {
        xPos = x;
        yPos = y;
        width = w;
        height = h;
        color = c;
    }

    public void draw(Graphics window)
    {
      window.setColor(color);
      window.fillRect(getX(), getY(), getWidth(), getHeight());
    }

    //get methods
    public int getWidth()
    {
       return width;
    }

    public int getHeight()
    {
       return height;
    }

    //toString
    public String toString()
    {
       String complete = getX() + " " + getY() + " " + getWidth() + " " + getHeight() + " java.awt.Color[r=" +     color.getRed() + ", g=" + color.getGreen() + ", b=" + color.getBlue() + "]";
       return complete;
    }
}

这是我必须实现的接口类:

public interface Locatable
{
    public void setPos( int x, int y);
    public void setX( int x );
    public void setY( int y );

    public int getX();
    public int getY();
}

我还没有关于接口/实现的正式指令,因此,我不确定需要做什么才能使第一个类正确运行

1 个答案:

答案 0 :(得分:2)

实现接口时,必须实现该接口中声明的所有方法。 界面是您的实施类必须完全填写的合同。在您的情况下,您的实施类阻止实施以下方法来完全填写合同

public void setPos( int x, int y);
public void setX( int x );
public void setY( int y );

public int getX();
public int getY();

public class Block implements Locatable {
     public void setPos( int x, int y){
       // your implementatioon code
      }
      public void setX( int x ) {


        // your implementatioon code
      }
     public void setY( int y ){

 // your implementatioon code
}
public int getX(){


 // your implementatioon code
 return (an int value);
}
public int getY(){


 // your implementatioon code
  return (an int value);
}

}

编辑:从评论中为你的NPE。

你从未初始化你的Color对象。并试图在你的toString方法中调用一个方法。

private Color color;

像这样初始化

 private Color color = new Color(any of the Color constructors);

点击此处查看Color API