java – 接口中没有setter方法
发布时间:2020-12-15 02:57:19 所属栏目:Java 来源:网络整理
导读:我有一个实现接口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;
我有一个实现接口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; } } 在接口B中,我只有getter方法但没有setter方法,尽管A类有它. 所以当我这样做时:B ref = new A();,这段代码会起作用,我将如何设置单词? 解决方法
如果接口确实暴露了它,则必须转换回原始类型
if (ref instanceof A) ((A) ref).setWords(words); else // something else. 更好的解决方案是将方法添加到接口. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容