2016-02-12 121 views
0

原谅我,接口仍然是我的一个新概念。我试图创建一个简单的重新主题的“乒乓”风格的游戏。我现在正在进行初始设置,在那里我只是在屏幕上创建个别模块,稍后我将在另一个课程中操作。抽象类难点:继承从接口

我写的所有构造函数,的getMethods,setMethods和接口,我想这个类使用。但是,当我尝试编译并运行类及其运行程序时,我从IDE中得到一个错误,指出“块不是抽象的,并且不覆盖Locatable中的抽象方法getY()”。

的getY()是内接口可定位

我试图使该类抽象,并解决该问题对于这个类。然而,在我的runner类中,我无法将对象从runner发送到原始类,因为现在它正试图发送它的类是抽象的。

这是我遇到的问题类的开头:

public class Block implements Locatable { 
//instance variables 
private int xPos; 
private int yPos; 

private int width; 
private int height; 

private Color color; 

public Block() 
{ 
    xPos = 0; 
    yPos = 0; 
    width = 0; 
    height = 0; 
} 

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

public Block(int x, int y, int wdth, int ht, Color col) 
{ 
    xPos = x; 
    yPos = y; 
    width = wdth; 
    height = ht; 
    color = col; 
} 

public void setBlockPos(int x, int y) 
{ 
    xPos = x; 
    yPos = y; 
} 

public void setXPos(int x) 
{ 
    xPos = x; 
} 

public void setYPos(int y) 
{ 
    yPos = y; 
} 

public void setWidth(int wdth) 
{ 
    width = wdth; 
} 

public void setHeight(int ht) 
{ 
    height = ht; 
} 
public void draw(Graphics window) 
{ 
    window.setColor(color); 
    window.fillRect(getX(), getY(), getWidth(), getHeight()); 
} 

public int getXPos() 
{ 
    return xPos; 
} 

public int getYPos() 
{ 
    return yPos; 
} 

public int getWidth() 
{ 
    return width; 
} 

public int getHeight() 
{ 
    return height; 
} 

public String toString() 
{ 
    return "" + xPos + " " + yPos + " " + width + " " + height; 
} 

} 

这是我的界面,我试图在类中使用上面:

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

这是我的亚军类,测试这是工作:

class BlockTestOne { 
public static void main(String args[]) 
{ 
    Block one = new Block(); 
    out.println(one); 

    Block two = new Block(50,50,30,30); 
    out.println(two); 

    Block three = new Block(350,350,15,15,Color.red); 
    out.println(three); 

    Block four = new Block(450,50,20,60, Color.green); 
    out.println(four); 
} } 

有什么我需要在界面o在我的'块'类?

+0

你的格挡类的实例必须实现从接口 – MartinS

+0

@MartinS你可以给我实现这些接口的一般语法的一个例子的方法是什么?在这整个界面的事情仍然是新的。 –

+0

'interface I {public void f(); }' 然后实现类必须实现函数 'C类实现I {@Overrides public void f(){...}}' – MartinS

回答

0

您已经使用在接口的类,但“SETY”“setYPos”。你的X和Y获得者和制定者有类似的问题。

+0

简单的修复,这就是我一直在寻找的。谢啦 –

-1

让我们看看你的类分组码。

+0

刚刚添加了'Block'代码,以便您查看 –

0

既然要实现在Block类可定位的接口。 根据合同,Block需要为接口中定义的所有方法提供实现。

0

一个抽象类不能被实例化,让你无论是要实现在块中的所有的接口方法,或创建一个从块扩展另一个类,并实现抽象方法,或实现模块内嵌的抽象方法,这里是最后一个选项

Block one = new Block(){ 
    @override 
    public int getY(){ 
     //do stuff 
    } 
}; 

http://www.tutorialspoint.com/java/java_abstraction.htm