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 10. Object-Oriented Programming

In this chapter, we will discover that, in Kotlin, classes are fundamental to just about everything and, in fact, just about everything is a class.

We have already talked about reusing other people's code, specifically the Android API, but in this chapter, we will really get to grips with how this works and learn about object-oriented programming (OOP) and how to use it.

In this chapter, we will cover the following topics:

  • Introduction to OOP and the three key topics of encapsulation, polymorphism, and inheritance

  • Basic classes, including how to write our first class including adding properties for data/variable encapsulation and functions to get things done

  • Explore visibility modifiers that further aid and refine encapsulation

  • Learn about constructors that enable us to quickly prepare our classes to be turned into usable objects/instances

  • Code a Basic Classes mini app to put in to practice everything we have learned in this chapter

If you try to memorize...

Introducing OOP


In Chapter 1, Getting Started with Android and Kotlin, we mentioned that Kotlin was an object-oriented language. An object-oriented language requires us to use OOP; it isn't an optional extra, it's part of Kotlin.

Let's find out a little bit more.

What is OOP exactly?

OOP is a way of programming that involves breaking our requirements down into chunks that are more manageable than the whole.

Each chunk is self-contained, and potentially reusable, by other programs, while working together as a whole with the other chunks.

These chunks are what we have been referring to as objects. When we plan/code an object, we do so with a class. A class can be thought of as the blueprint of an object.

We implement an object of a class. This is called an instance of a class. Think about a house blueprint – you can't live in it, but you can build a house from it; so, you build an instance of it. Often, when we design classes for our apps, we write them to represent real-world things.

However, OOP...

Basic classes


There are two main steps involved with classes. First, we must declare our class, and then we can bring it to life by instantiating it into an actual useable object. Remember, the class is just a blueprint, and you must use the blueprint to build an object before you can do anything with it.

Declaring a class

Classes can be of varying sizes and complexities depending upon what its purpose is. Here is the absolute simplest example of a class declaration.

Remember that we most often declare a new class in a file of its own with the same name as the class.

Note

We will cover some exceptions to the rule throughout the rest of the book.

Let's have a look at three examples of declaring a class:

// This code goes in a file named Soldier.kt
class Soldier

// This code would go in a file called Message.kt
class Message

// This code would go in a file called ParticleSystem.kt
class ParticleSystem

Note

Note that we will do a full working project to practice at the end of this chapter. There...

Visibility modifiers


Visibility modifiers are used to control the access/visibility of variables, functions, and even whole classes. As we will see, it is possible to have variables, functions, and classes with different levels of access depending upon where in the code the access is being attempted from. This allows the designers of a class to practice good encapsulation and make just the functionality and data they choose available to users of the class. As a slightly contrived but useful example, the designers of a class used to talk to a satellite and get GPS data wouldn't allow access to the dropOutOfTheSky function.

These are the four access modifiers in Kotlin.

Public

Declaring classes, functions, and properties as public means that they are not hidden/encapsulated at all. In fact, the default visibility is public and everything we have seen and used so far is, therefore, public. We could make this explicit by using the public keyword before all our class, function, and property declarations...

Constructors


Throughout this chapter we have been instantiating objects (instances of classes) and we have gone into some depth about the various syntax. There is one small part of the code we have been ignoring until now. This next code we have seen several times before, but I have highlighted a small part of it so we can discuss it further:

val soldier = Soldier()

The brackets on the end of the code that initialize the object looks just like code from the previous chapter when we called a function (without any parameters). That is, in fact, exactly what is happening. When we declare a class, Kotlin provides (behind the scenes) a special function called a constructor that prepares the instance.

So far in this chapter, we have declared and initialized all our instances in a single line each. Often, we will need to use some more logic in initialization, and often we will need to allow the code that initializes an instance of a class to pass in some values (just like a function). This is the...

Basic classes app and using the init block


You can get the completed code for this app in the code download. It is in the Chapter10/Basic Classes folder. But it is most useful to read on to create your own working example.

We will create a few different classes using what we have learned throughout this chapter to put the theory in to practice. We will also see our first example of how classes can interact with each other by passing a class as a parameter into the function of another class. We know how to do this in theory already, we just haven't seen it in practice yet.

We will also see another way to initialize our data when the class is first instantiated by using an init block.

We will create a small app that plays with the idea of simulating ships, docks, and sea battles.

Note

The output for the apps in this chapter and the next will be just text to the logcat window. In Chapter 12, Connecting our Kotlin to the UI and Nullability, we will bring together everything we learned in the first...

Introduction to references


There might be a nagging thought in your mind at this point. Look at the two functions from the Shipyard class again:

fun serviceDestroyer(destroyer: Destroyer){
        destroyer.serviceShip()
}

fun serviceCarrier(carrier: Carrier){
        carrier.serviceShip()
}

When we called those functions and passed the friendlyDestroyer and friendlyCarrier to their appropriate service… function, we saw, from the before and after output, that the values inside the instances were changed. Usually, if we want to keep the result from a function, we need to use the return value. What is happening is that, unlike a function that has regular types as parameters, when we pass an instance of a class, we are really passing a reference to the instance itself – not just copies of the values within it, but the actual instance.

Furthermore, all the different ship-related instances were declared with val, so how did we change any of the properties at all? The short answer to this conundrum...

Summary


We have, at last, written our first class. We have seen that we can implement a class in a file of the same name as the class. The class itself doesn't do anything until we instantiate an object/instance of the class. Once we have an instance of the class, we can use its special variables, called properties, and its non-private functions. As we proved in the Basic Classes app, every instance of a class has its own distinct properties, just as when you buy a car made in a factory, you get your very own steering wheel, satnav, and go-faster stripes. We have also bumped into the concept of references, which means that, when we pass an instance of a class to a function, the receiving function has access to the actual instance.

All this information will raise more questions. OOP is like that. So, let's try and consolidate all this class stuff by taking a much closer look at inheritance in the next chapter.

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