Inheritance vs Extension functions

This post was originally posted at https://agrawalsuneet.github.io/blogs/inheritance-vs-extension-functions/ and reposted on Medium on 3rd Dec 2019.

Inheritance

Inheritance is nothing but extending a class and adding functionality to it. You can add properties (variables) as well as functions in the extending class. You can access the variables of extending (Base) class if they are not private (protected or internal or public) can override them if they are not final (open variables) or you can override the functions also.

open class Person(var firstName : String,
protected var lastName : String) {
open fun getFullDetails() : String {
return "$firstName $lastName"
}
}
class Student : Person {
var rollNumber = 0

constructor(firstName : String,
lastName: String,
rollNumber : Int)
: super (firstName, lastName){
this.rollNumber = rollNumber
}

override fun getFullDetails() : String {
return "$firstName $lastName with Roll number as $rollNumber"
}
}
var student = Student ("Suneet", "Agrawal", 12)
println(student.getFullDetails())

Extension Function

Extension functions are the functions where you add a functionality to an existing class by just adding a function without extending the class and this will be resolved statically and all the objects of that class can use it.

class Employee(var firstName : String, var lastName : String) {
}
fun Employee.getFullDetails() : String {
return "$firstName $lastName"
}
var emp = Employee("Suneet", "Agrawal")
println(emp.getFullDetails())

Merits of Extension functions

  • Can add functionality to a final class also. The class need not be a non-final (open) class.
  • Can add functionality without subclassing that means the object reference and the implementation can be of your base class.

Demerits of Extension functions

  • Can’t access the protected variables/properties or functions of your base class.
  • Can’t add any new variable/properties in your extension functions. You can add a property by just writing getter and setter but only without backing field. So basically you can’t add a field in the base class.

Merits of Inheritance

  • Can add new properties, override functions (non-final) of the base class.
  • Can access all protected variables and functions of the base class.

Demerits of Inheritance

  • Can’t extend a final class.

--

--

https://agrawalsuneet.github.io/

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store