Object-Oriented Programming II: Inheritance and Blueprints
8 min read
Object-Oriented Programming II: Inheritance and Blueprints blueprints π
Welcome back! In our last session, we started exploring the world of Object-Oriented Programming (OOP). Now, let's dive deeper and uncover how we can create more complex and organized structures using interfaces, inheritance, and abstract classes. Think of this as moving from building with individual LEGO bricks to using pre-designed LEGO kits and custom blueprints!
1. Interfaces: Defining Contracts and Default Implementations π€
The Problem: Imagine you're building a new video game. You'll have different characters: a Knight, an Archer, and a Mage. All of these characters need to be able to attack, but their attack methods will be different. How do you ensure that every character class you create will definitely have an attack() function? You could just remember to add it every time, but what if you forget? Or what if you misspell it? This is where interfaces come to the rescue.
What is an Interface?
An interface in Kotlin is a blueprint for a class. It defines a set of methods and properties that a class must implement. It's like a contract; if a class says it will implement an interface, it's promising to provide the functionality defined in that interface.
Let's see it in action.
// Defining an interface
interface Attacker {
fun attack()
}
// Implementing the interface in different classes
class Knight : Attacker {
override fun attack() {
println("The Knight swings a sword!")
}
}
class Archer : Attacker {
override fun attack() {
println("The Archer fires an arrow!")
}
}
class Mage : Attacker {
override fun attack() {
println("The Mage casts a fireball!")
}
}
fun main() {
val knight = Knight()
val archer = Archer()
val mage = Mage()
knight.attack()
archer.attack()
mage.attack()
}In this example, the Attacker interface declares an attack() function. The Knight, Archer, and Mage classes all implement this interface, which means they are all required to have their own attack() function. This ensures consistency and predictability in our code.
Default Implementations
What if we want to provide a default way to do something? Let's say we also want our characters to be able to block, but not every character will have a special way of blocking. We can provide a default implementation directly in the interface.
interface Attacker {
fun attack()
fun block() {
println("The character raises a shield.")
}
}
class Knight : Attacker {
override fun attack() {
println("The Knight swings a sword!")
}
// The Knight uses the default block()
}
class Archer : Attacker {
override fun attack() {
println("The Archer fires an arrow!")
}
override fun block() {
println("The Archer dodges to the side.")
}
}
fun main() {
val knight = Knight()
val archer = Archer()
knight.attack()
knight.block() // Uses the default implementation
archer.attack()
archer.block() // Uses its own implementation
}Here, the Knight uses the default block() implementation from the Attacker interface, while the Archer provides its own custom block() method. This is incredibly useful for adding new functionality without breaking existing classes that implement the interface.
Fun Fact! π€ In the early days of Java (which heavily influenced Kotlin), interfaces couldn't have default implementations. This feature was added in Java 8 and was a game-changer, making interfaces much more flexible. Kotlin had this feature from the beginning!
2. Inheritance: The 'open' Keyword and Superclasses π
The Problem: Let's stick with our game. We have our Knight, Archer, and Mage. They are all characters, so they will likely share some common properties and behaviors. For example, every character will have a name and a certain amount of health. We could add these properties to each class individually, but that would be repetitive. If we wanted to add a new property, like level, we'd have to add it to every single character class. There must be a better way!
What is Inheritance?
Inheritance is a mechanism where a new class (the subclass or child class) derives properties and methods from an existing class (the superclass or parent class). This allows for code reuse and creates a clear hierarchy.
In Kotlin, classes are final by default, which means they cannot be inherited from. To allow a class to be a superclass, you must mark it with the open keyword.
Let's create a Character superclass.
open class Character(val name: String, var health: Int) {
fun takeDamage(damage: Int) {
health -= damage
println("$name took $damage damage. Health is now $health.")
}
}
class Knight(name: String, health: Int) : Character(name, health) {
fun charge() {
println("$name is charging!")
}
}
class Archer(name: String, health: Int) : Character(name, health) {
fun aim() {
println("$name is aiming...")
}
}
fun main() {
val knight = Knight("Sir Lancelot", 100)
val archer = Archer("Legolas", 80)
knight.takeDamage(20)
archer.takeDamage(15)
knight.charge()
archer.aim()
}In this example, both Knight and Archer inherit from Character. This means they automatically get the name and health properties, as well as the takeDamage() method, without us having to write that code in each class. They also have their own specific methods, charge() and aim().
Under the Hood: When a subclass is created, the constructor of the superclass is called first to initialize its properties. That's why we have to call
Character(name, health)in the declaration of theKnightandArcherclasses.
3. Overriding Methods and Properties π
The Problem: Our Character class is great, but what if different character types have special reactions to taking damage? For instance, a Mage might have a magical shield that reduces incoming damage. The current takeDamage() method is the same for everyone. How can we change the behavior of an inherited method?
What is Overriding?
Overriding allows a subclass to provide a specific implementation of a method or property that is already provided by its superclass. Just like with classes, methods and properties in Kotlin are final by default. To allow a method or property to be overridden, you must mark it with the open keyword in the superclass. The subclass then uses the override keyword.
Let's give our Mage a magic shield.
open class Character(val name: String, var health: Int) {
open fun takeDamage(damage: Int) {
health -= damage
println("$name took $damage damage. Health is now $health.")
}
}
class Mage(name: String, health: Int, private val magicShield: Int) : Character(name, health) {
override fun takeDamage(damage: Int) {
val actualDamage = damage - magicShield
if (actualDamage > 0) {
health -= actualDamage
println("$name's magic shield blocked $magicShield damage.")
println("$name took $actualDamage damage. Health is now $health.")
} else {
println("$name's magic shield blocked all the damage!")
}
}
}
fun main() {
val genericCharacter = Character("Generic Hero", 100)
val mage = Mage("Gandalf", 70, 10)
genericCharacter.takeDamage(20)
mage.takeDamage(20)
}Now, when takeDamage() is called on a Mage object, it's the overridden version that gets executed, which takes the magicShield into account. The super keyword can be used to call the superclass's implementation of a method if needed.
4. Abstract Classes: Partial Implementations ποΈ
The Problem: Our Character class is useful, but you can create an instance of it. What does a "generic" character do in our game? It doesn't have a specific attack. We want to define what a Character is in general, but we don't want to allow anyone to create a plain Character. We also want to force every character type to have an attack() method, but the implementation will be different for each one.
What is an Abstract Class?
An abstract class is a class that cannot be instantiated on its own. It's meant to be a base for other classes. Abstract classes can have both abstract methods (methods without a body) and regular methods with implementations. If a class has an abstract method, the class itself must be declared as abstract.
Let's make our Character class abstract.
abstract class Character(val name: String, var health: Int) {
abstract fun attack() // Abstract method - no implementation
fun takeDamage(damage: Int) {
health -= damage
println("$name took $damage damage. Health is now $health.")
}
}
class Knight(name: String, health: Int) : Character(name, health) {
override fun attack() {
println("$name swings a mighty sword!")
}
}
class Archer(name: String, health: Int) : Character(name, health) {
override fun attack() {
println("$name fires a precise arrow!")
}
}
fun main() {
// val character = Character("Some Guy", 100) // This will cause an error! Cannot create an instance of an abstract class.
val knight = Knight("Sir Galahad", 120)
val archer = Archer("Robin Hood", 85)
knight.attack()
archer.attack()
}Now, our Character class serves as a more robust blueprint. It defines that every character must have an attack() method, but it leaves the "how" up to the subclasses. It also provides the concrete takeDamage() method that all characters can use.
Abstract Class vs. Interface
You might be thinking that abstract classes sound a lot like interfaces. You're right, they are similar! Here's a quick rundown of the main differences in common industry usage:
| Feature | Interface | Abstract Class |
|---|---|---|
| State | Cannot store state (no properties with backing fields). | Can store state (can have properties with backing fields). |
| Constructors | Cannot have constructors. | Can have constructors. |
| Multiple Inheritance | A class can implement multiple interfaces. | A class can only inherit from one abstract class. |
| When to use | When you want to define a "can do" relationship (e.g., a Bird can fly, a Plane can fly). Use an interface to define a contract for behavior. |
When you want to define an "is a" relationship (e.g., a Knight is a Character, an Archer is a Character). Use an abstract class to provide a common base with some shared implementation. |
In modern Kotlin, with default implementations in interfaces, the lines can sometimes blur. A good rule of thumb is to favor interfaces unless you need to share state or have a constructor in your base type.
References for Further Reading π
Challenge
You are designing a system for magical creatures in a game. Your task is to create a class hierarchy using interfaces, abstract classes, and inheritance.
Requirements:
Create an Interface:
- Define an interface named
Summonable. - It should have one abstract method:
summon(): String. - It should also have a method with a default implementation:
dismiss(): Stringthat returns the string "The creature vanishes.".
- Define an interface named
Create an Abstract Class:
- Define an
abstract classnamedMagicalFamiliarthat implements theSummonableinterface. - Its primary constructor should accept a
name: StringandmaxHealth: Int. - It must contain the following properties:
name: String(from the constructor)maxHealth: Int(from the constructor)currentHealth: Int, initialized to the value ofmaxHealth.
- It should have a concrete,
openmethodtakeDamage(damage: Int)that subtracts the damage fromcurrentHealth. - It must define an
abstractmethodprimaryAttack(): String. - It must
overridethesummon()method to return a string like "Summoning [name]!", where[name]is the creature's name property.
- Define an
Create Concrete Classes:
FireSprite:- A class that inherits from
MagicalFamiliar. - Its constructor should only take a
nameand call the parent constructor with a fixedmaxHealthof50. - Implement the
primaryAttack()method to return "Throws a scorching fireball!".
- A class that inherits from
StoneGolem:- A class that inherits from
MagicalFamiliar. - Its constructor should only take a
nameand call the parent constructor with a fixedmaxHealthof150. - Implement the
primaryAttack()method to return "Slams the ground with a stone fist!". overridethetakeDamage(damage: Int)method. This new version should reduce all incoming damage by 5 before calling the superclass'stakeDamagemethod. The damage should not go below zero.overridethedismiss()method to return "The Stone Golem crumbles back into the earth.".
- A class that inherits from
Expected result
Your code should correctly define a complete class hierarchy with the following structure:
- An interface
Summonablewith one abstract methodsummonand one default methoddismiss. - An
abstract class MagicalFamiliarthat correctly:- Implements the
Summonableinterface. - Has the specified primary constructor and properties (
name,maxHealth,currentHealth). - Contains an
openconcrete methodtakeDamage. - Contains an
abstractmethodprimaryAttack. - Overrides the
summonmethod.
- Implements the
- A final class
FireSpritethat:- Inherits from
MagicalFamiliar. - Correctly calls the
superconstructor with a hardcoded health value. - Provides a concrete implementation for
primaryAttack.
- Inherits from
- A final class
StoneGolemthat:- Inherits from
MagicalFamiliar. - Correctly calls the
superconstructor with a hardcoded health value. - Provides a concrete implementation for
primaryAttack. - Correctly overrides both the
takeDamageanddismissmethods, calling the super implementation where necessary.
- Inherits from