Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Android Studio 4.2 Development Essentials - Kotlin Edition

You're reading from  Android Studio 4.2 Development Essentials - Kotlin Edition

Product type Book
Published in Aug 2021
Publisher Packt
ISBN-13 9781803231549
Pages 804 pages
Edition 1st Edition
Languages
Author (1):
Neil Smyth Neil Smyth
Profile icon Neil Smyth

Table of Contents (94) Chapters

1. Introduction 2. Setting up an Android Studio Development Environment 3. Creating an Example Android App in Android Studio 4. Creating an Android Virtual Device (AVD) in Android Studio 5. Using and Configuring the Android Studio AVD Emulator 6. A Tour of the Android Studio User Interface 7. Testing Android Studio Apps on a Physical Android Device 8. The Basics of the Android Studio Code Editor 9. An Overview of the Android Architecture 10. The Anatomy of an Android Application 11. An Introduction to Kotlin 12. Kotlin Data Types,Variables and Nullability 13. Kotlin Operators and Expressions 14. Kotlin Flow Control 15. An Overview of Kotlin Functions and Lambdas 16. The Basics of Object Oriented Programming in Kotlin 17. An Introduction to Kotlin Inheritance and Subclassing 18. An Overview of Android View Binding 19. Understanding Android Application and Activity Lifecycles 20. Handling Android Activity State Changes 21. Android Activity State Changes by Example 22. Saving and Restoring the State of an Android Activity 23. Understanding Android Views, View Groups and Layouts 24. A Guide to the Android Studio Layout Editor Tool 25. A Guide to the Android ConstraintLayout 26. A Guide to Using ConstraintLayout in Android Studio 27. Working with ConstraintLayout Chains and Ratios in Android Studio 28. An Android Studio Layout Editor ConstraintLayout Tutorial 29. Manual XML Layout Design in Android Studio 30. Managing Constraints using Constraint Sets 31. An Android ConstraintSet Tutorial 32. A Guide to using Apply Changes in Android Studio 33. An Overview and Example of Android Event Handling 34. Android Touch and Multi-touch Event Handling 35. Detecting Common Gestures Using the Android Gesture Detector Class 36. Implementing Custom Gesture and Pinch Recognition on Android 37. An Introduction to Android Fragments 38. Using Fragments in Android Studio - An Example 39. Modern Android App Architecture with Jetpack 40. An Android Jetpack ViewModel Tutorial 41. An Android Jetpack LiveData Tutorial 42. An Overview of Android Jetpack Data Binding 43. An Android Jetpack Data Binding Tutorial 44. An Android ViewModel Saved State Tutorial 45. Working with Android Lifecycle-Aware Components 46. An Android Jetpack Lifecycle Awareness Tutorial 47. An Overview of the Navigation Architecture Component 48. An Android Jetpack Navigation Component Tutorial 49. An Introduction to MotionLayout 50. An Android MotionLayout Editor Tutorial 51. A MotionLayout KeyCycle Tutorial 52. Working with the Floating Action Button and Snackbar 53. Creating a Tabbed Interface using the TabLayout Component 54. Working with the RecyclerView and CardView Widgets 55. An Android RecyclerView and CardView Tutorial 56. A Layout Editor Sample Data Tutorial 57. Working with the AppBar and Collapsing Toolbar Layouts 58. An Android Studio Primary/Detail Flow Tutorial 59. An Overview of Android Intents 60. Android Explicit Intents – A Worked Example 61. Android Implicit Intents – A Worked Example 62. Android Broadcast Intents and Broadcast Receivers 63. An Introduction to Kotlin Coroutines 64. An Android Kotlin Coroutines Tutorial 65. An Overview of Android Services 66. Implementing an Android Started Service – A Worked Example 67. Android Local Bound Services – A Worked Example 68. Android Remote Bound Services – A Worked Example 69. An Android Notifications Tutorial 70. An Android Direct Reply Notification Tutorial 71. Foldable Devices and Multi-Window Support 72. An Overview of Android SQLite Databases 73. The Android Room Persistence Library 74. An Android TableLayout and TableRow Tutorial 75. An Android Room Database and Repository Tutorial 76. Accessing Cloud Storage using the Android Storage Access Framework 77. An Android Storage Access Framework Example 78. Video Playback on Android using the VideoView and MediaController Classes 79. Android Picture-in-Picture Mode 80. An Android Picture-in-Picture Tutorial 81. Making Runtime Permission Requests in Android 82. Android Audio Recording and Playback using MediaPlayer and MediaRecorder 83. Printing with the Android Printing Framework 84. An Android HTML and Web Content Printing Example 85. A Guide to Android Custom Document Printing 86. An Introduction to Android App Links 87. An Android Studio App Links Tutorial 88. A Guide to the Android Studio Profiler 89. An Android Biometric Authentication Tutorial 90. Creating, Testing and Uploading an Android App Bundle 91. An Overview of Android Dynamic Feature Modules 92. An Android Studio Dynamic Feature Tutorial 93. An Overview of Gradle in Android Studio Index

17. An Introduction to Kotlin Inheritance and Subclassing

In “The Basics of Object Oriented Programming in Kotlin” we covered the basic concepts of object-oriented programming and worked through an example of creating and working with a new class using Kotlin. In that example, our new class was not specifically derived from a base class (though in practice, all Kotlin classes are ultimately derived from the Any class). In this chapter we will provide an introduction to the concepts of subclassing, inheritance and extensions in Kotlin.

17.1 Inheritance, Classes and Subclasses

The concept of inheritance brings something of a real-world view to programming. It allows a class to be defined that has a certain set of characteristics (such as methods and properties) and then other classes to be created which are derived from that class. The derived class inherits all of the features of the parent class and typically then adds some features of its own. In fact, all classes in Kotlin are ultimately subclasses of the Any superclass which provides the basic foundation on which all classes are based.

By deriving classes we create what is often referred to as a class hierarchy. The class at the top of the hierarchy is known as the base class or root class and the derived classes as subclasses or child classes. Any number of subclasses may be derived from a class. The class from which a subclass is derived is called the parent class or superclass.

Classes need not only be derived from a root class. For example, a subclass...

17.2 Subclassing Syntax

As a safety measure designed to make Kotlin code less prone to error, before a subclass can be derived from a parent class, the parent class must be declared as open. This is achieved by placing the open keyword within the class header:

open class MyParentClass {

    var myProperty: Int = 0

}

With a simple class of this type, the subclass can be created as follows:

class MySubClass : MyParentClass() {

 

}

For classes containing primary or secondary constructors, the rules for creating a subclass are slightly more complicated. Consider the following parent class which contains a primary constructor:

open class MyParentClass(var myProperty: Int) {

             

}

In order to create a subclass of this class, the subclass declaration references any base class parameters while...

17.3 A Kotlin Inheritance Example

As with most programming concepts, the subject of inheritance in Kotlin is perhaps best illustrated with an example. In “The Basics of Object Oriented Programming in Kotlin” we created a class named BankAccount designed to hold a bank account number and corresponding current balance. The BankAccount class contained both properties and methods. A simplified declaration for this class is reproduced below and will be used for the basis of the subclassing example in this chapter:

class BankAccount {

 

    var accountNumber = 0

    var accountBalance = 0.0

    

    constructor(number: Int, balance: Double) {

        accountNumber = number

        accountBalance = balance

    }

    

    ...

17.4 Extending the Functionality of a Subclass

So far we have been able to create a subclass that contains all the functionality of the parent class. In order for this exercise to make sense, however, we now need to extend the subclass so that it has the features we need to make it useful for storing savings account information. To do this, we simply add the properties and methods that provide the new functionality, just as we would for any other class we might wish to create:

class SavingsAccount : BankAccount {

         var interestRate: Double = 0.0

 

    constructor(accountNumber: Int, accountBalance: Double) :

                           super(accountNumber, accountBalance)

 

    fun calculateInterest(): Double

   ...

17.5 Overriding Inherited Methods

When using inheritance it is not unusual to find a method in the parent class that almost does what you need, but requires modification to provide the precise functionality you require. That being said, it is also possible you’ll inherit a method with a name that describes exactly what you want to do, but it actually does not come close to doing what you need. One option in this scenario would be to ignore the inherited method and write a new method with an entirely new name. A better option is to override the inherited method and write a new version of it in the subclass.

Before proceeding with an example, there are three rules that must be obeyed when overriding a method. First, the overriding method in the subclass must take exactly the same number and type of parameters as the overridden method in the parent class. Second, the new method must have the same return type as the parent method. Finally, the original method in the parent class...

17.6 Adding a Custom Secondary Constructor

As the SavingsAccount class currently stands, it makes a call to the secondary constructor from the parent BankAccount class which was implemented as follows:

constructor(accountNumber: Int, accountBalance: Double) :

super(accountNumber, accountBalance)

Clearly this constructor takes the necessary steps to initialize both the account number and balance properties of the class. The SavingsAccount class, however, contains an additional property in the form of the interest rate variable. The SavingsAccount class, therefore, needs its own constructor to ensure that the interestRate property is initialized when instances of the class are created. Modify the SavingsAccount class one last time to add an additional secondary constructor allowing the interest rate to also be specified when class instances are initialized:

class SavingsAccount : BankAccount {

 

    var interestRate: Double = 0.0

 ...

17.7 Using the SavingsAccount Class

Now that we have completed work on our SavingsAccount class, the class can be used in some example code in much the same way as the parent BankAccount class:

val savings1 = SavingsAccount(12311, 600.00, 0.07)

 

println(savings1.calculateInterest())

savings1.displayBalance()

17.8 Summary

Inheritance extends the concept of object re-use in object oriented programming by allowing new classes to be derived from existing classes, with those new classes subsequently extended to add new functionality. When an existing class provides some, but not all, of the functionality required by the programmer, inheritance allows that class to be used as the basis for a new subclass. The new subclass will inherit all the capabilities of the parent class, but may then be extended to add the missing functionality.

lock icon The rest of the chapter is locked
You have been reading a chapter from
Android Studio 4.2 Development Essentials - Kotlin Edition
Published in: Aug 2021 Publisher: Packt ISBN-13: 9781803231549
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.
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 £13.99/month. Cancel anytime}