Mer*_*ary 6 java inheritance interface
我有一个实现接口B的具体类A.
B ref = new A();
Run Code Online (Sandbox Code Playgroud)
代码:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
在接口B中,我只有getter方法但没有setter方法,尽管A类有它.
所以当我这样做时:B ref = new A();这段代码会起作用,我将如何设置单词?
如果将setWords其定义为,您将无法调用ref B ref = ....
这是在声明变量(或使用强制转换)时需要使用确切类型的情况之一:
A ref = new A();
Run Code Online (Sandbox Code Playgroud)
或者:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
所以当我这样做时:B ref = new A();,这个代码会起作用吗......
是的,它会的.
......我将如何设置单词?
除非你:否则你将无法:
A的构造函数取词列表; 要么setWords()到B; 要么A对象的类型引用; 要么ref地A.其中,我会选择1-3中的一个.最后一个选项仅包括完整性.
如果接口确实公开了它,则必须转换回原始类型
if (ref instanceof A)
((A) ref).setWords(words);
else
// something else.
Run Code Online (Sandbox Code Playgroud)
更好的解决方案是将方法添加到接口中。