接口变量和实现类

Cla*_*ara 1 java

接口变量是否可以从实现类中分配变量?

Ste*_*n C 16

如果您问以下是否有效,那么答案是否定的:

public interface Foo {
    public int thing = 21;
    ...
}

public class FooImpl implements Foo {
    public void someMethod() {
        thing = 42;  // compilation error here
    }
}
Run Code Online (Sandbox Code Playgroud)

原因是它Foo.thing不是变量变量.它是含蓄 finalstatic; 即它是一个静态常数.

如果您希望Foo接口的实例实现"变量",那么接口应该定义getter和setter方法,并且这些方法应该在实现类中实现(例如),以便在声明的私有实例变量中保存相应的状态.班级.

另一方面,如果您询问以下内容是否有效,则答案为是:

public interface Foo {
    ...
}

public class FooImpl implements Foo {
    ...
}

public class Test {
    FooImpl fi = ...;
    Foo f = fi;  // OK.
}
Run Code Online (Sandbox Code Playgroud)