1

Can an interface variable be assigned a variable from an implementing class?

1
  • 1
    What exactly did u intend to know ? Elaborate. Commented Jan 30, 2011 at 2:06

4 Answers 4

16

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.
}
Sign up to request clarification or add additional context in comments.

Comments

3

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

1

If you need an interface that specifies the ability to get/set a variable, include getVariable/setVariable methods in your interface as appropriate, so that the interface implementer is required to implement them.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.