我有一个查询,下面是声明常量的接口,我在这里也可以有瞬态吗?如果没有,那是什么原因我们不能在接口内有瞬态变量,我熟悉瞬态在序列化过程中的作用。 .
interface OlympicMedal {
static final String GOLD = "Gold";
static final String SILVER = "Silver";
static final String BRONZE = "Bronze";
}
我建议在接口中使用枚举而不是常量。您使用的模式在 pre java 5 代码中很常见。然后引入了枚举。它引入了类型安全,是推荐的方法。
如果您正在序列化并想要瞬态属性,那么这可能有助于序列化枚举
接口中定义的所有变量都是隐式“静态”的;“瞬态”仅对非“静态”字段有意义:因此您所问的没有意义。
All variables declared in an interface are public
, static
and final
. In fact those are the only possible modifiers that are possible in an Interface
For the same reason, you really don't have to explicitly specify these modifiers when you're creating a variable in an interface
. In your example, you could've just said:
interface OlympicMedal {
String GOLD = "Gold";
String SILVER = "Silver";
String BRONZE = "Bronze";
}
Firstly, interface only provides a contract in terms of the operations to be defined by the classes implementing that interface. It doesn't carry state and so you cannot declare member variables in an interface (what you declared in your interface definition are constants). So, there is no possibility of a transient member in an interface.