我有一个实现类 Bag 的类,该类具有容纳无限数量字符串的空间,并且支持接口(interface)中的方法。我必须实现以下类(class):
Simplebag(此类包含按添加顺序排列的字符串) BagWithoutRepetitions(此类与 Simplebag 的作用相同,只是不存在重复项)
我的问题是我不知道类的设置如何工作,以及如何引用包含方法的类。
到目前为止我已经有了这个,但无法用它来测试任何东西,因为我确信我错误地引用了这些类:
public interface Bag {
public static void main(String[] args) {
}
class SimpleBag implements Bag {
ArrayList<String> bag = new ArrayList<String>();
}
这是界面
import java.util.ArrayList;
public interface Bag {
/** Add the string "str" to the strings in the bag as the last
* element. It str was added then the method returns "true" and
* "false" otherwise.
* @param str
* @return true iff succesfully added
*/
public boolean addString(String str);
/** Removes all ocurrences of "str" from the bag.
* If "str" occurred at least once in the bag then the method
* returns "true" and "false" otherwise.
* @param str
* @return true iff str occured at least once
*/
public boolean removeAllOccurrences(String str);
/** Returns the string which currently is at the position given
* by "index". In case the operation cannot be conducted, the
* method returns "null".
* @param index
* @return string at index or null
*/
public String getString(int index);
/** returns the number of elements currently in the bag.
* Indexing starts with 0.
*
* @return number of elements in the bag
*/
public int noOfElements();
}
我该如何继续?
最佳答案
SimpleBag
需要是一个单独的类。
public class SimpleBag implements Bag {
}
类SimpleBag
需要包含Bag
中出现的所有方法。
这是一个不完整的骨架。
public class SimpleBag implements Bag {
public boolean addString(String str) {
// TODO: Complete.
return false; // To make sure this code compiles.
}
public boolean removeAllOccurrences(String str) {
// TODO: Complete.
return false; // To make sure this code compiles.
}
public String getString(int index) {
// TODO: Complete.
return null; // To make sure this code compiles.
}
public int noOfElements() {
// TODO: Complete.
return 0; // To make sure this code compiles.
}
}
类似地创建另一个类BagWithoutRepetitions
,它也包含接口(interface)Bag
中的所有方法。这是一个更小的骨架。
public class BagWithoutRepetitions implements Bag {
}
然后您可以编写另一个类来测试您的 SimpleBag
(和 BagWithoutRepetitions
)类。
这是该测试器类的框架。
public class BagTester {
public static void main(String[] args) {
Bag bag = new SimpleBag();
bag.addString("George");
bag.addString("Best");
bag.addString("Northern");
bag.addString("Ireland");
bag.addString("Manchester");
bag.addString("United");
int count = bag.noOfElements();
System.out.printf("Bag contains %d elements.%n", count);
}
}
尝试完成以上骨架。编辑您的问题并添加您将编写的代码并指出您遇到困难的地方。
祝你好运!
关于java - 在类中实现接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59006587/