Can an interface variable be assigned a variable from an implementing class?
4 Answers
If you are asking if the following will work, then the answer is No:
public interface Foo {
public int thing = 21;
...
}
public class FooImpl implements Foo {
public void someMethod() {
thing = 42; // compilation error here
}
}
The reason is that Foo.thing is NOT a variable variable. It is implicitly final and static; i.e. it is a static constant.
If you want instances of the Foo interface to implement a "variable", then the interface should define getter and setter methods, and these methods should be implemented in an implementing class (for example) to hold the corresponding state in a private instance variable declared by the class.
On the other hand, if you are asking if the following will work, then the answer is Yes:
public interface Foo {
...
}
public class FooImpl implements Foo {
...
}
public class Test {
FooImpl fi = ...;
Foo f = fi; // OK.
}
Comments
No, it can not.
Every field that is declared in an interface is implicitly public static final, i.e., a constant. Thus, you can not assign anything to it from an implementing class.
See also:
Comments
Interface : System requirement service.
In interface, variable are by default assign by public,static,final access modifier. Because :
public : It happen some-times that interface might placed in some other package. So it need to access the variable from anywhere in project.
static : As such incomplete class can not create object. So in project we need to access the variable without object so we can access with the help of
interface_filename.variable_name
final : Suppose one interface implements by many class and all classes try to access and update the interface variable. So it leads to inconsistent of changing data and affect every other class. So it need to declare access modifier with final.
Due to this design of interface variable its implementing class cannot assign or update value of variable. It can only access the interface variable.