Java – there is no setter method in the interface
•
Java
I have a concrete class a that implements interface B
B ref = new A();
code:
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; } }
In interface B, I only have getter method but no setter method, although class A has it
So when I do this: B ref = new a();, This code will work. How will I set the word?
Solution
If the interface does expose it, it must be converted back to the original type
if (ref instanceof A) ((A) ref).setWords(words); else // something else.
A better solution is to add methods to the interface
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码