简体   繁体   English

为什么抽象类字段不是隐式静态的

[英]Why abstract class fields are not static implicitly

According to this question https://stackoverflow.com/questions/2430756/why-are-interface-variables-static-and-final-by-defaul t 根据这个问题https://stackoverflow.com/questions/2430756/why-are-interface-variables-static-and-final-by-defaul t

the accepted answer says, that interface fields are implicitly static because we cannot instantiate it. 公认的答案说,接口字段是隐式静态的,因为我们无法实例化它。

But shouldn't it be the same case for abstract classes as well? 但是抽象类也应该不一样吗? since abstract classes cannot be instantiated, shouldn't the fields of that abstract class also be static? 由于不能实例化抽象类,因此该抽象类的字段也应该是静态的吗?

I know they are not static, but can somebody explain me the reason. 我知道它们不是静态的,但是有人可以向我解释原因。

That's not the reason interface fields are static by default. 这不是默认情况下接口字段为静态的原因。 The reason is that an interface may not define instance fields. 原因是接口可能未定义实例字段。

An abstract class can, so if fields were static by default, you could not declare normal, instance fields without introducing an additional useless instance keyword. 抽象类可以,因此,如果默认情况下字段是静态的,则您不能在不引入其他无用instance关键字的情况下声明普通实例字段。 And that would be extremely confusing. 这将非常令人困惑。

Abstract classes cannot be instantiated, but they're intended to be used as base classes for concrete classes, which in turn can be instantiated. 抽象类不能实例化,但是它们打算用作具体类的基类,而具体类又可以实例化。

The main reason why interface fields have to be static is not that interfaces cannot be instantiated; 接口字段必须为静态的主要原因不是接口无法实例化。 it's because a class can inherit from multiple interfaces, and therefore inherit state from multiple places. 这是因为一个类可以从多个接口继承,因此可以从多个位置继承状态。 There are all kinds of tricky situations which can (and do) arise in languages like C++ which allow that. 在诸如C ++这样的语言中,可能会(而且确实)出现各种棘手的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM