简体   繁体   中英

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

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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