Reputation: 2072
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?
Upvotes: 0
Views: 81
Reputation: 42586
You cannot do this for an interface. However, it is possible to modify a static final
variable in a class:
public abstract class I {
static final int val;
static
{
val = 1;
}
}
import java.lang.reflect.*;
public class NotFinal
{
public static void main(String args[]) throws Exception
{
System.out.println(I.val); // Before: 1
Field field = I.class.getDeclaredField("val");
field.setAccessible(true);
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(null, 2);
System.out.println(I.val); // After: 2
}
}
Output:
1
2
Note that this does not work if you assign the value in the declaration, i.e.
static final int val = 1;
because the compiler treats this differently (as a constant) - see this answer.
Upvotes: 0
Reputation: 178411
You cannot. Interface variables are static
and final
by default.
A final
variable is a variable that cannot be changed during the life of the object.
A static
vairable 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:
int getVal();
void setVal(int val);
And make the implementing classes implement the methods - so you will be able to use the variable with the getVal()
and setVal()
methods.
Upvotes: 4