我有一个实现接口(interface) B 的具体类 A。
B ref = new A();
代码:
public interface B{
public abstract String[] getWords();
}
public class A implements B {
private String[] words = new String[] {};
public void setWords(String[] words){
this.words = words;
}
public String[] getWords(){
return this.words;
}
}
在接口(interface) B 中,我只有 getter 方法而没有 setter 方法,尽管类 A 有它。
所以当我这样做时:B ref = new A();
,这段代码会起作用吗?我将如何设置单词?
最佳答案
如果 ref 被定义为 B ref = ...
,您将无法调用 setWords
。
这是在声明变量(或使用强制转换)时需要使用确切类型的情况之一:
A ref = new A();
或者:
- 您可以创建一个扩展 B 并包含两种方法的接口(interface) C,并让 A 实现 C。
- 您可以在 A 中提供一个构造函数,它采用
String[] words
参数来初始化您的words
字段,并且根本不提供 setter。
我个人倾向于后一种选择:
public class A implements B {
private final String[] words;
public A(String[] words) {
this.words = words;
}
public String[] getWords() {
return this.words;
}
}
关于java - 接口(interface)中没有设置方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13950648/