英文:
Implementing an Interface with an abstract method
问题
我正试图使用public class MyStringSet implements StringSet{}
来实现一个接口,但我一直得到一个错误,指出"MyStringSet不是抽象的,并且没有在StringSet中覆盖抽象方法getCapacity()"。我该如何在不出现此错误的情况下实现这个接口?
public interface StringSet {
public void resize(int larger);
public void insert(String entry);
public void remove(String target);
public String getRandomItem();
public String getFirstItem();
public boolean contains(String target);
public boolean is_empty();
public int inventory();
public int getCapacity();
}
英文:
I am trying to implement an interface using public class MyStringSet implements StringSet{}
but I keep getting an error that "MyStringSet is not abstract and does not override abstract method getCapacity() in StringSet". How would I be able to impletment this interface without getting this error?
public interface StringSet {
public void resize(int larger);
public void insert(String entry);
public void remove(String target);
public String getRandomItem ();
public String getFirstItem ();
public boolean contains(String target);
public boolean is_empty( );
public int inventory( );
public int getCapacity( );
}
答案1
得分: 0
简短回答:很可能,您的实现并没有真正地“实现”那些抽象方法。接口就像是洞。实现填补了这些洞,如果没有填补,您必须将扩展的类声明为抽象类,因为它让一些这些“洞”保持开放。它们仍然必须由不再是抽象的真正实现来填充。
以下是您的情况的简单实现:
public class MyStringSet implements StringSet {
public void resize(int larger) {}
public void insert(String entry) {}
public void remove(String target) {}
public String getRandomItem () {return null;}
public String getFirstItem () {return null;}
public boolean contains(String target) {return false;}
public boolean is_empty( ) {return false;}
public int inventory( ) {return 0;}
public int getCapacity( ) {return 0;}
}
英文:
Short answer: most likely, your implementation is not really "implementing" those abstract methods. An interface is like holes. The implementation fills those holes and if not, you have to declare your extending class as abstract, as it let some of those "holes" open. They still have to be filled by a real implementation which is not abstract anymore.
Here is an easy implementation for your case:
public class MyStringSet implements StringSet {
public void resize(int larger) {}
public void insert(String entry) {}
public void remove(String target) {}
public String getRandomItem () {return null;}
public String getFirstItem () {return null;}
public boolean contains(String target) {return false;}
public boolean is_empty( ) {return false;}
public int inventory( ) {return 0;}
public int getCapacity( ) {return 0;}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论