Reasoning behind open modifier for overriden methods

154 Views Asked by At

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?

2

There are 2 best solutions below

2
On BEST ANSWER

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.

2
On

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.