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

ColorAPIについてはこちらを確認してください

于 2012-11-08T21:47:31.360 に答える