Kotlin, a statically typed, cross-platform language developed by Jet Brains, is a more expressive, safer, and quicker alternative to Java for coding. Google officially supports Kotlin, making it the go-to language for Android app development.
In Kotlin and other Object-Oriented languages, the ‘abstract’ keyword is used to declare abstract classes, immediately before the class declaration. An important facet to note is that these classes cannot be instantiated directly; they solely serve as blueprints for other classes. This attribute emphasizes code reusability, paving the way for well-structured, extensible software.
Abstract classes hold a pivotal role in defining common properties and behaviors for subclasses to inherit and implement. They can encompass abstract properties and abstract methods — members without an implementation— permitting different classes to provide their unique implementations. In contrast with regular (or non-abstract) classes, abstract classes can contain abstract members.
Here's a snapshot of how to use it in code:
1abstract class Person { 2 abstract var height: Int 3 abstract var age: Int 4 abstract fun speak() 5}
In Kotlin, you cannot create objects of an abstract class. In other words, instances of an abstract class cannot be created. This necessitates abstract methods to be implemented by a child class or a derived class.
A Kotlin abstract class can possess both abstract and non-abstract methods (functions). When declared as abstract, properties are required to be overridden in the derived class. The class body is tagged as ‘abstract’, identifying that it’s an abstract class. Providing the implementation for declared abstract methods and properties becomes the responsibility of derived or child classes.
Here's an example of an abstract class Person possessing an abstract member function speak():
1abstract class Person { 2 abstract fun speak() 3}
In this context, any concrete subclass extending Person must provide concrete implementations for all the abstract methods defined in the Person class. This ensures the explicit implementation of these abstract methods.
The declaration for an abstract class in Kotlin includes the keyword ‘abstract class’, followed by the class name.
Let's look at how to extend an abstract class:
1class Child: Person() { 2 override fun speak() { 3 println("I am a child.") 4 } 5}
In the Child class that extends the Person abstract class, the speak() method has been implemented. The override keyword signifies that this function overrides the method from its parent abstract class.
Abstract classes have a pivotal role in Kotlin as they engineer paths for abstractions. They lay out methods to declare properties and methods that the classes cannot provide a default implementation for, impelling derived classes to implement these methods and functions independently.
The influential concept of Object-Oriented Programming (OOP) - Inheritance, is set ablaze by these abstract classes. They empower the child class to inherit features from the parent abstract class while maintaining flexibility for the child class to implement its specific functionalities.
The keyword abstract is pivotal to abstract classes in Kotlin. Declaring a Kotlin Abstract variable or a Kotlin Abstract property can be accomplished with the usage of the Abstract keyword. Abstract members, including properties, variables, and methods, do not possess an implementation in their class, granting derived classes the autonomy to provide the implementation.
Here, age is an abstract property that will eventually be overridden in the derived class. Similarly, speak() is an abstract method that has to be defined in the child classes that implement this abstract class. Remember, abstract methods are not allowed to have a body and are always open, which means they can be overridden.
In Kotlin, a certain order is followed when abstract variables and properties are declared in an abstract class. These properties do not need to be initialized at the point of declaration in the abstract class. Instead, they only need to be declared, and their actual initialization is accomplished in the child class.
In the same vein, an abstract function must only be declared, not defined in an abstract class. Both abstract properties and abstract methods in an abstract class must be overridden in the child class, with the child class providing the implementation details.
Here's an example:
1abstract class Animal { 2 // Declaring an abstract variable 3 abstract var animalName: String 4 5 // Declaring an abstract function 6 abstract fun sound() 7} 8 9class Dog : Animal() { 10 override var animalName = "Doggy" 11 12 override fun sound() { 13 print("Dog sounds Woof Woof") 14 } 15} 16 17fun main(args: Array<String>) { 18 // Dog is deriving from Animal 19 val my pet = Dog() 20 21// Printing Dog's Name 22println("My Dog's name is ${mypet.animalName}") 23mypet.sound() 24}
In this animal kingdom-themed snippet, we have an abstract class Animal with an abstract variable animalName and an abstract function sound(). In the Dog class, which derives from Animal, we provide an implementation for both animalName and sound().
This example encapsulates the usage and traversal order of abstract variables when utilized in a Kotlin abstract class. Abstract properties in a class are often initialized via the class's primary constructor, defined in the class header, initializing the class instances and properties.
An abstract function in Kotlin is a function declared within an abstract class that doesn't contain a method body. Instead, it seeks the implementation of its properties and methods from the classes that subsequently inherit from this abstract class.
Here is an abstract class Animal with an abstract method speak():
1abstract class Animal { 2 abstract fun speak() 3}
Let's create another class Dog that extends the Animal abstract class and provides its own implementation of the speak() method:
1class Dog: Animal() { 2 override fun speak() { 3 println("The dog says: Woof Woof!") 4 } 5} 6 7fun main(args: Array<String>) { 8 val mydog = Dog() 9 mydog.speak()// Will print "The dog says: Woof Woof!" 10}
The Dog class is extending the 'Animal' abstract class and providing its definition for the speak() method - "The dog says: Woof Woof!". This embodies the abstraction and polymorphism in Kotlin whereby methods are declared in the parent abstract class, but their behavior varies in different classes. This is accomplished by using the override keyword before the function declaration in a derived class.
To implement an abstract class in Kotlin, you are required to extend the abstract class and provide definitions for the abstract methods. While implementing an abstract class, a derived class doesn't need to implement default methods. However, all abstract methods must be overridden in a derived class. Here's how it looks in the code:
1abstract class Animal { 2 abstract fun speak() 3 fun eat() { 4 println("Animal is eating") 5 } 6} 7 8class Dog: Animal() { 9 override fun speak() { 10 println("The dog says: Woof Woof!") 11 } 12} 13 14fun main(args: Array<String>) { 15 val mydog = Dog() 16 mydog.speak()// Will print "The dog says: Woof Woof!" 17 mydog.eat()// Will print "Animal is eating" 18}
In the Dog class, we’re not only able to speak(), but also eat() -- since the latter is a non-abstract method in Animal which has a default implementation. This way, we can maintain the same interface while making it easy to implement common behavior. Further, by utilizing the same abstract class, multiple derived classes can extend it to share common functionality. This enhances code reusability and maintains a consistent interface across different types of animals.
Kotlin, being a statically typed programming language, does not allow a class to extend multiple classes, therefore, you cannot extend multiple abstract classes either. This is due to the well-known multiple inheritance problem in Object Oriented Programming.
1abstract class ClassA { 2 abstract fun displayA() 3} 4abstract class ClassB { 5 abstract fun displayB() 6} 7 8class MyClass : ClassA, ClassB {// This will raise an error 9 ... 10}
The workaround for this issue in Kotlin is the usage of Interfaces. A Kotlin class can implement multiple interfaces, so if you need to "extend" multiple classes, restructuring them as interfaces (wherever possible) is the way to go.
Both interfaces and abstract classes allow you to declare methods without implementing them. However, the Kotlin interface differs from the Kotlin abstract class in several crucial aspects:
• A class can implement multiple interfaces, but it can only extend a single abstract class.
• Interface members are 'open' by default, but they have no actual implementation. Instead, they provide a method signature or blueprint to be implemented by classes implementing the interface.
• Kotlin interfaces cannot hold state. They can declare properties but these need to be abstract or provide accessor implementations.
• Unlike abstract classes, interfaces are not constructors and hence cannot be instantiated.
Abstract classes in Kotlin are exceedingly beneficial in architecture and software development, especially when dealing with large-scale apps with intricate class hierarchies. They yield a standard template for classes that share common functionalities, promoting clean and DRY (Don't Repeat Yourself) code.
They are extremely useful when:
• Designing large functional units.
• Modeling toolkits and frameworks where the user extends your base classes.
• You need to create a class that provides a common mechanism for multiple subclasses while preserving a certain level of implementation flexibility.
With this knowledge, you can now effectively leverage Kotlin abstract classes to create more versatile and manageable code architectures.
Kotlin Abstract Classes offer a compelling way to create a blueprint for multiple classes. They are unlike regular classes since they cannot be instantiated, and they can contain both abstract and non-abstract methods and properties. The onus lies with the child class or derived class to implement any abstract elements.
It's of utmost importance to remember that such classes cannot extend multiple classes and can only extend one class. To extend multiple classes, the recommended approach is to use interfaces. Abstract classes hold an indispensable role in effective architecture, promoting clean and reusable code.
By understanding Kotlin abstract classes, you have now mastered one of the fundamental principles of object-oriented programming which forms the building blocks of Kotlin. Keep on coding and exploring more with Kotlin!
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.