我需要为接口中描述的方法创建一个类,如下所示:
public interface MyStringInterface {
// Sets the value of the current string
public void setString(String str);
// Returns the current string
public String getString();
}
当我使用如下方法创建一个类时,总会出现此错误,并且不会让我继续。我究竟做错了什么?我该怎么办?
package seclass.assgn;
public class MyString implements MyStringInterface{
static String name;
public static void main(String[] args) {
setString("This is my sentence");
System.out.println(getString());
}
public void setString(String str){
name = str;
}
public String getString() {
return name;
}
}
答案 0 :(得分:1)
您需要MyString
-
public static void main(String[] args) {
MyString my = new MyString();
my.setString("This is my sentence");
System.out.println(my.getString());
}
也
static String name;
应该是
private String name;
或者,如果您不想要实例,只需使用
public static void main(String[] args) {
name = "This is my sentence";
System.out.println(name);
}
答案 1 :(得分:1)
首先,你不必重复"公众"在接口中。
public interface MyStringInterface {
void setString(String str);
String getString();
} // end of class MyStringInterface
然后你必须创建一个实现的对象:
public class MyString implements MyStringInterface {
String name;
public static void main(String[] args) {
new MyString().top();
}
void top() {
setString("This is my sentence.");
System.out.println(getString());
}
@Override
public void setString(String str) {
this.name = str;
}
@Override
public String getString() {
return this.name;
}
} // end of class MyString