0

When overriding a method in Kotlin, the base class defining the method and the method itself must be declared open.

After overriding the method the derived class is final by default, while the overridden method is open by default. From the reference documentation:

A member marked override is itself open, i.e. it may be overridden in subclasses. If you want to prohibit re-overriding, use final.

I wonder why the Kotlin-Team made this design decision instead of making the overridden method final as well, which is the default for the derived class and every non-overriden method. I couldn't find any hint while searching the web?

Does anyone have a link to the reasoning behind this design decision or may motivate it?

Harmlezz
  • 7,972
  • 27
  • 35

2 Answers2

2

It's just much more practical. If the method is open, it means that it's designed to be overridden, and such methods are normally overridden multiple times in a class hierarchy. And marking the derived class as open is much easier than repeating the open modifier for all overridden methods as well.

yole
  • 92,896
  • 20
  • 260
  • 197
  • *such methods are normally overridden multiple times in a class hierarchy*. How do we know? And if this would be the case, why is the derived class not open as well by default? Otherwise the open modifier of the method makes no sense, right? – Harmlezz Dec 03 '18 at 09:53
  • We know this from looking at existing class hierarchies. Think about something like JComponent. A specific component class is not necessarily designed to be extended, but if it is, it's very likely that its derived classes will want to override the same methods (painting, event handling etc.) that this class overrode from JComponent. – yole Dec 03 '18 at 10:18
1

You could argue that these properties are actually correlating. If the class is explicitly marked as open, all properties and methods which were defined as open are treated the same way in all subclasses. If the subclass is not open, the methods are not overridable, regardless of their own modifiers.

As you might have noticed as well, all modifiers of the original definition are inherited. So you don't have to duplicate that information, only when you want to change the signature, you'll have to define it explicitly.

tynn
  • 38,113
  • 8
  • 108
  • 143
  • I can see your point. While the derived class is `final` everything behaves as before. If the derived class is open, it is just an intermediate layer of the base class, not changing any signatures. And if I want to make things `final` I have to add it to the overridden methods of my `open` intermediate class. Is this what you meant? – Harmlezz Dec 03 '18 at 10:15
  • @Harmlezz yes, I like how you state it. – tynn Dec 03 '18 at 11:47