#26 Abstract class and interface in kotlin | Kotlin tutorial | Kotlin Bootcamp for programmers

preview_player
Показать описание
Abstract classes are always open; you don't need to mark them with open. Properties and methods of an abstract class are non-abstract unless you explicitly mark them with the abstract keyword. That means subclasses can use them as given. If properties or methods are abstract, the subclasses must implement them.
When to use abstract classes versus interfaces
The examples above are simple, but when you have a lot of interrelated classes, abstract classes and interfaces can help you keep your design cleaner, more organized, and easier to maintain.

As noted above, abstract classes can have constructors, and interfaces cannot, but otherwise they are very similar. So, when should you use each?

When you use interfaces to compose a class, the class's functionality is extended by way of the class instances that it contains. Composition tends to make code easier to reuse and reason about than inheritance from an abstract class. Also, you can use multiple interfaces in a class, but you can only subclass from one abstract class.
Composition often leads to better encapsulation, lower coupling (interdependence), cleaner interfaces, and more usable code. For these reasons, using composition with interfaces is the preferred design. On the other hand, inheritance from an abstract class tends to be a natural fit for some problems. So you should prefer composition, but when inheritance makes sense Kotlin lets you do that too!
Рекомендации по теме