4 Classes, objects, and interfaces

 

This chapter covers

  • Classes and interfaces
  • Nontrivial properties and constructors
  • Data classes
  • Class delegation
  • Using the object keyword

In this chapter, you’ll gain a deeper understanding of working with classes and interfaces in Kotlin. You already saw the basic syntax for declaring a class in section 2.2, and you know how to declare methods and properties, use simple primary constructors (aren’t they nice?), and work with enums. But there’s a lot more to see and learn on the topic! Kotlin’s classes and interfaces differ a bit from what you might be used to from Java: for example, interfaces can contain property declarations. Kotlin’s declarations are final and public, by default. In addition, nested classes aren’t inner by default; they don’t contain an implicit reference to their outer class.

For constructors, the short primary constructor syntax works great for the majority of cases, but Kotlin also comes with full syntax that lets you declare constructors with nontrivial initialization logic. The same works for properties: the concise syntax is nice, but you can easily define your own implementations of accessors.

The Kotlin compiler can generate useful methods to avoid verbosity. Declaring a class as a data class instructs the compiler to generate several standard methods for this class. You can also avoid writing delegating methods by hand, since the delegation pattern is supported natively in Kotlin.

4.1 Defining class hierarchies

4.1.1 Interfaces in Kotlin

4.1.2 Open, final, and abstract modifiers: Final by default

4.1.3 Visibility modifiers: Public by default

4.1.4 Inner and nested classes: Nested by default

4.1.5 Sealed classes: Defining restricted class hierarchies

4.2 Declaring a class with nontrivial constructors or properties

4.2.1 Initializing classes: Primary constructor and initializer blocks

4.2.2 Secondary constructors: Initializing the superclass in different ways

4.2.3 Implementing properties declared in interfaces

4.2.4 Accessing a backing field from a getter or setter