My question is how can I write setter/getter methods and static fields in an interface and implement it in another class.
An example:
public interface MyInterface {
int number = 0;
public int setNumber(int num);{
}
}
// Use it
public MyClass implements MyInterface{
...
public int setNumber(int num) {
number = num; // Error, Why?
}
}
I get error on number = num but it get no error in the setName(...) method!
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.And
setNumbershould return avoidinstead ofint. For getting I suggest you to addint getNumber().As you can see, only
setNumberis part ofMyInterface. Consumers do not need to know about how the number is stored, therefore it is an implementation detail.Besides, in Java you name classes and interfaces in
PascalCaserather thancamelCase.