I've a concrete class A that implements an 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 the interface B, I've only getter method but no setter method though the class A has it.
So when I do this : B ref = new A();
, will this code work and how will I set words?
A marker interface is an interface that doesn't have any methods or constants inside it. It provides run-time type information about objects, so the compiler and JVM have additional information about the object. A marker interface is also called a tagging interface.
You cannot define instance fields in interfaces (unless they are constant - static final - values, thanks to Jon), since they're part of the implementation only. Thus, only the getter and setter are in the interface, whereas the field comes up in the implementation.
Getter and setter methods (also known as accessors) are dangerous for the same reason that public fields are dangerous: They provide external access to implementation details. What if you need to change the accessed field's type? You also have to change the accessor's return type.
All of these methods are referred to as getters and setters, even when a backing variable is used. It is not possible to access any controller variables without a getter or setter.
You won't be able to call setWords
on ref if it is defined as B ref = ...
.
This is one of the cases where you need to use the exact type when declaring the variable (or use a cast):
A ref = new A();
Alternatively:
String[] words
argument to initialise your words
field, and not provide a setter at all.I would personally favour the latter option:
public class A implements B {
private final String[] words;
public A(String[] words) {
this.words = words;
}
public String[] getWords() {
return this.words;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With