Design Converter
Education
Last updated on May 8, 2024
Last updated on May 8, 2024
In object-oriented programming, one of the fundamental concepts is inheritance. In Kotlin, we refer to this as "Kotlin extends".
When we say "extends" in Kotlin, we talk about the process whereby a new class (derived class) can acquire the members (variables and methods) of an existing class (base class). This is a crucial aspect of object-oriented programming (OOP) that provides benefits like code reusability and design patterns' implementation.
The Kotlin extends notion paves the way for efficient coding practices and better code organization.
In this blog, we will explore the Kotlin extends class concept, primarily focusing on the base class, derived class, primary constructor, and how Kotlin implements inheritance.
In the context of Kotlin extends, a base class is an existing class from which other classes can inherit properties and functions. The base class often acts as the fundamental building block for creating other classes in Kotlin. Consider the following example for a better understanding:
1open class Person(val name: String, val age: Int) { 2 fun walk() { 3 // Walking functionality 4 } 5 fun talk() { 6 // Talking functionality 7 } 8}
'Person' plays the role of the base class here that we can use to shower other classes with all the features used within it. Here, val name and val age are two properties defined in the Person class. fun walk() and fun talk() are two functions or member functions that provide walking and talking functionality.
The keyword open allows us to make our Person class inheritable. In Kotlin, classes are final by default, which means they cannot be inherited unless you specify them as open.
Focusing on Kotlin extends class, let's look deeper into Kotlin class inheritance. Derived classes in Kotlin can inherit members (functions and properties) from the base class. This is achieved using a colon : and referencing the base class constructor right after the name of the derived class.
1open class Person(val name: String, val age: Int) 2 3class Employee(name: String, age: Int, val salary: Int) : Person(name, age)
Here, Person is the base class, and Employee is the derived class extending the base Person class. val salary is a new property added to the Employee class. By employing Kotlin inheritance, we can create objects from the Employee class and access all the properties and functions of both Employee and Person (base class).
When a derived class aims to override a member function or property declaration from its base class, the override modifier is required before the member function or property in the derived class. Consider the following example for illustration:
1open class Person(var name: String, var age: Int) { 2 open fun display() { 3 // Display person's information 4 } 5} 6class Employee(name: String, age: Int, var salary: Int) : Person(name, age) { 7 override fun display() { 8 // Display employee's information 9 } 10}
In this example, the display function is present in both the base and derived class. But in the derived class, the display function is prefixed with the 'override' keyword to indicate that it overrides the member function of its base class.
This was just a quick understanding of how Kotlin extends class and what it means by Kotlin inheritance. The blog has some more exciting stuff to unwrap. So keep reading.
Taking the discussion on extends in Kotlin further, let's decode this mechanism in depth. In Kotlin, the extend keyword doesn't exist as it does in other languages, like Java. Instead, we use a colon : to indicate inheritance, which might seem unusual to programmers coming from a Java background.
Consider the following example:
1open class Person(val name: String, val age: Int) 2class Athlete(name: String, age: Int, val sport: String) : Person(name, age)
When the Athlete class extends the Person class, it implicitly receives val name and val age properties, and hence the Athlete becomes a Person with additional features. This is how Kotlin extends a class, keeping the OOP principles intact while introducing some new functionality.
In Kotlin, the primary constructor is the part of the class header. It's declared after the class name and can have optional parameters. This constructor plays an essential role when the Kotlin class inherits from a base class.
Here's an example of a primary constructor used in a base class and a derived class:
1open class Person(val name: String) { 2 open fun show() { 3 println("Name is $name") 4 } 5} 6 7class Employee(name: String, val salary: Int) : Person(name) { 8 override fun show() { 9 println("Name is $name and salary is $salary") 10 } 11} 12 13fun main() { 14 val person = Person("John") 15 val employee = Employee("Sam", 5000) 16 17 person.show()// prints "Name is John" 18 employee.show()// prints "Name is Sam and salary is 5000" 19}
In the Kotlin example above, fun main contains the main functionality where objects for the base and derived class are created, and member functions are called. The name parameter provided to the Employee class object also gets passed to its base class Person through the primary constructor, showcasing how the constructor plays an essential role in Kotlin inheritance.
In Kotlin, the extends mechanism is implemented differently, which can seem peculiar initially but is quite efficient when grasped correctly. This different approach redefines the inheritance model while building upon the existing principles of Object-Oriented Programming.
In the standard inheritance concept, the derived class inherits the base class members. However, in Kotlin, functionality from one class is incorporated into another using the concept of extension functions. This process enhances the code's maintainability and reduces the complications often associated with classic inheritance.
1open class Person { 2 open fun show() { 3 println("Displaying Person") 4 } 5} 6 7class Employee : Person() { 8 override fun show() { 9 println("Displaying Employee") 10 } 11} 12 13fun main() { 14 val person = Person() 15 person.show() // prints "Displaying Person" 16 17 val employee = Employee() 18 employee.show() // prints "Displaying Employee" 19}
In the example above, the fun show in the Employee class overrides the show function in the Person class. Mentioning the override keyword is necessary as it communicates to the compiler that you're planning to override the function from the base class.
So, extends in Kotlin not only rethinks the inheritance paradigm but also ensures the code remains clean and maintainable.
In Kotlin extends class setup, a derived class (or subclass) is a type of class that 'extends' a base class. It generally adds new properties and functions or modifies the existing behavior inherited from the base class. Let's understand this with an example.
In the given Kotlin example:
1open class Person(val name: String, val age: Int) 2 3class Student(name: String, age: Int, val grade: String) : Person(name, age) { 4 fun study() { 5 println("$name is studying.") 6 } 7} 8 9fun main() { 10 val student = Student("Robert", 16, "10th") 11 student.study() // prints "Robert is studying." 12}
The Student class is derived from the Person base class and introduces a new function study() in addition to its inherited attributes, name, and age.
Using the fun main function, we create an object of type Student, which can access all the properties and functionalities of both Student (derived class) and Person (base class).
To modify an inherited method in the derived class, we use the override keyword as shown in previous examples. The members marked open in the base class can be overridden in the derived classes in Kotlin.
Kotlin also provides data classes specifically designed to hold only data. Although data classes cannot be open (as per Kotlin's constraints), we can use composition over inheritance for better code organization and structure.
Let's learn it with an example:
1data class Name(val firstname: String, val lastname: String) 2class Person(val name: Name, val age: Int) 3 4fun main() { 5 val person = Person(Name("John", "Doe"), 25) 6 println(person) // prints "Person(name=Name(firstname=John, lastname=Doe), age=25)" 7}
Here, the Name is a data class, and the Person class includes a property of type Name, enabling the Person class to benefit from the auto-generated functionalities like toString(), hashCode(), etc., of a data class. This method opens up new possibilities outside the realm of traditional inheritance.
While Kotlin extends, it also redefines the way class extension works, especially compared to languages like Java. Many developers wonder if this reimagining of inheritance makes Kotlin incompatible with Java, or if Kotlin is trying to align with Java while improving upon some of its shortcomings.
The apparent deviation from the classic model does not mean that Kotlin re-invents the wheel; it adds a bit of innovation while maintaining a backbone of tested OOP principles. For example, the primary constructor in Kotlin provides a concise way to initialize classes. The open modifier provides better control, giving the developer the freedom to decide which classes or members should be open for inheritance, optimizing the codebase's scope, and reducing unnecessary override operations.
Java's extends keyword finds its Kotlin equivalent in ":", enabling efficient inheritance between classes. Other concepts, like the override keyword, are pretty much aligned, reflecting the strength of having a common superclass.
Therefore, Kotlin extends and reinterprets the inheritance approach while being interoperable with Java, paving the way for a more flexible, reduced-effort coding experience.
In conclusion, Kotlin's approach to inheritance, including how Kotlin extends classes, provides a thoughtful evolution in the world of Object-Oriented Programming. It combines efficient syntax, strategic use of keywords like open and override, and new concepts, including extension functions, that revitalize the traditional inheritance model.
Developers of all levels can appreciate Kotlin's nuanced take on inheritance for its flexibility and emphasis on code readability and maintainability. Thus, Kotlin stands out without straying from core OOP principles offering a more efficient coding journey. Happy Kotlin coding!
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.