I know that interface can have only static and final values implemented inside it.. But is there any loophole by which I can change the value of
a variable using interface?? The question may be absurd, but I m helpless since its my requirement. Here is the example piece of code..
public interface I {
int val = 1;
int changeValue();
}
Class A implements I{
int changeValue(){
val = 2 ;
return 0;
}
}
How to change the value of ‘val’ using interface?
Can I do something similar to:
val = changeValue();
Is there anything equivalent to do this functionality in an interface?
You cannot. Interface variables are
staticandfinalby default.A
finalvariable is a variable that cannot be changed during the life of the object.A
staticvairable is a class variable – it means there is only one value of it for all instances of the class (or interface in this case).Thus – you only have one value for
I.x– and this value cannot be changed.What you might want to do, is define methods in your interface:
And make the implementing classes implement the methods – so you will be able to use the variable with the
getVal()andsetVal()methods.