0

这是我的课程,一切都完成了:

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();
}

我还没有关于接口/实现的正式指导,因此,我不确定需要做什么才能让第一堂课正常运行

4

1 回答 1

2

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

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);

在这里检查颜色 API

于 2012-11-08T21:47:31.360 回答