Reader small image

You're reading from  Android Programming with Kotlin for Beginners

Product typeBook
Published inApr 2019
Reading LevelIntermediate
PublisherPackt
ISBN-139781789615401
Edition1st Edition
Languages
Right arrow
Author (1)
John Horton
John Horton
author image
John Horton

John Horton is a programming and gaming enthusiast based in the UK. He has a passion for writing apps, games, books, and blog articles. He is the founder of Game Code School.
Read more about John Horton

Right arrow

Chapter 11. Inheritance in Kotlin

In this chapter, we will get to see inheritance in action. In fact, we have already seen it, but now we will examine it more closely, discuss the benefits, and write classes that we can inherit from. Throughout the chapter, I will show you several practical examples of inheritance, and at the end of the chapter we will improve our naval battle simulation from the previous chapter and show how we could have saved lots of typing and future debugging by using inheritance.

We will cover the following topics in this chapter:

  • Object-oriented programming (OOP) and inheritance

  • Using inheritance with open classes

  • Overriding functions

  • A bit more about polymorphism

  • Abstract classes

  • Inheritance example app

To get started, let's talk a little more about the theory.

OOP and inheritance


We have seen how we can reuse our own code, and other people's code, by instantiating/creating objects from classes. But this whole OOP thing goes even further than that.

What if there is a class that has loads of useful functionality in it, but is not exactly what we want? Think about when we wrote the Carrier class. It was so close to the Destroyer class that we could have almost copy-and-pasted it. We can inherit from a class, and then further refine or add to how it works and what it does.

You might be surprised to hear that we have done this already. In fact, we have done this with every single app we have created. When we use the : syntax, we are inheriting. You may recall this code from the MainActivity class:

class MainActivity : AppCompatActivity() {

Here, we are inheriting from the AppCompatActivity class all its functionality – or, more specifically, all the functionality that the designers of the class want us to have access to.

We can even override a function...

Using inheritance with open classes


Some terminology that would be useful to learn at this point is that the class that is inherited from is known as the super or base class. Other common ways to refer to this relationship is parent and child class. The child class inherits from the parent class.

By default, a class cannot be inherited from. It is called a final class – not open for extending or inheriting from. It is very straightforward, however, to change a class so it can be inherited from. All we need to do is add the open keyword to the class declaration.

Basic inheritance examples

Look at this next code, which uses the open keyword with the class declaration and enables the class to be inherited from:

open class Soldier() {

    fun shoot () {
        Log.i("Action","Bang bang bang")
    }
}

Note

All the examples from this chapter can be found as completed classes in the Chapter11/Chapter Examples folder.

We can now go ahead and create objects of the Soldier type and call the shoot function...

More polymorphism


We already know that polymorphism means many forms, but what does it mean to us?

Boiled down to its simplest, it means the following:

Note

Any subclass can be used as part of code that uses the super class.

This means that we can write code that is easier to understand, and simpler to change.

Also, we can write code for the super class and rely on the fact that no matter how many times it is subclassed, the code will still work within certain parameters. Let's discuss an example.

Suppose that we want to use polymorphism to help write a zoo management app. We will probably want to have a function, such as feed. Let's also say we have Lion, Tiger, and Camel classes, which all inherit from a parent class called Animal. We will also probably want to pass a reference to the animal to be fed into the feed function. This might seem like we need to write a feed function for each and every type of Animal.

Instead, however, we can write polymorphic functions with polymorphic arguments...

Classes using the Inheritance example app


We have looked at the way we can create hierarchies of classes to model the system that fits our app. So, let's build a project to improve upon the naval battle we had in the previous chapter.

Create a new project called Basic Classes with Inheritance Example using the Empty Activity template. As you have come to expect, the completed code can be found in the Chapter11 folder.

This is what we are going to do:

  • Put most of the functionality of the Carrier and Destroyer classes into a Ship super class.

  • Inherit from the Ship class for both Carrier and Destroyer, and therefore save a lot of code maintenance.

  • Use polymorphism to adapt the serviceShip function in the Shipyard class so that it takes Ship as a parameter, and can therefore service any instance that inherits from Ship, thereby reducing the number of functions in the class.

  • We will also see that not only is there less code achieving the same functionality as before, but it is more encapsulated than...

Summary


If you haven't memorized everything, or if some of the code seemed a bit too in-depth, then you have still succeeded.

If you just understand that OOP is about writing reusable, extendable, and efficient code through encapsulation, inheritance, and polymorphism, then you have the potential to be a Kotlin master.

Simply put, OOP enables us to use other people's code, even when those other people were not aware of exactly what we would be doing at the time they did the work.

All you have to do is keep practicing, because we will constantly be using these same concepts over and over again throughout the book, so you do not need to have even begun to master them at this point.

In the next chapter, we will be revisiting some concepts from this one, as well as looking at some new aspects of OOP and how it enables our Kotlin code to interact with our XML layouts.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Android Programming with Kotlin for Beginners
Published in: Apr 2019Publisher: PacktISBN-13: 9781789615401
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at AU $19.99/month. Cancel anytime

Author (1)

author image
John Horton

John Horton is a programming and gaming enthusiast based in the UK. He has a passion for writing apps, games, books, and blog articles. He is the founder of Game Code School.
Read more about John Horton