开发者

Modifiable constants inside an interface

开发者 https://www.devze.com 2023-04-01 13:25 出处:网络
I know that based on the Java tutorials: An interface can contain constant declarations in addition to method declarations. All constant values defined in an interface are implicitly public, static,

I know that based on the Java tutorials:

An interface can contain constant declarations in addition to method declarations. All constant values defined in an interface are implicitly public, static, and final. Once again, these modifiers can be omitted.

Is it possible to make the values inside an interface to be shared and modifiable by all the classes t开发者_C百科hat implement the said interface?


In theory, yes, if you use a mutable type for your "constant", e.g. AtomicReference.
However, it would be an awful design!

public interface MyInterface{
    AtomicReference<String> NAME = new AtomicReference<String>("Fred");
}


public static void main(final String[] args){
    System.out.println(MyInterface.NAME);
    MyInterface.NAME.set("Jim");
    System.out.println(MyInterface.NAME);
}

Output:

Fred
Jim

You could use Collections, Maps, Arrays or any other type that mutably holds values for this pattern, however I would seriously request you to rethink it.


Is it possible to make the values inside an interface to be shared and modifiable by all the classes that implement the said interface?

The class that implements the interface sees the constant but constant are final (instantiated once and never redeclared). If your constant is an object like List, you can add/remove objects from it.


you should not want this :), it would be a big hack.

Use abstract class instead interfaces for create modifiable values, — off course if you can use abstract class in your design.


Your interface could declare accessors for the values that you want to change. Rather than directly referring to constants, you could call the accessors to get and set the values. These values would actually be members of the classes that implemented the interface. While they might or might not be static, they don't have to be final.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号