Search⌘ K
AI Features

Nested and Inner Classes

Explore how Kotlin supports nested and inner classes within class hierarchies. Understand the advantages of inner classes accessing private members of the outer class and how to implement interfaces efficiently. Discover techniques including the inner keyword, this and super expressions, and anonymous inner classes to manage state and design in Kotlin.

In the previous example, you may wonder why TV didn’t directly implement the Remote interface instead of having a separate class TVRemote that implements the interface. Having a separate class like TVRemote instead of directly implementing the interface has a few pros and cons. Let’s discuss the pros first, then the cons, and arrive at a solution to give us the best of both options.

Pros and cons of interfaces

The first benefit of having a TVRemote is that we may have multiple instances of TVRemote for a single instance of TV, much like how cars and garage doors have multiple remotes. This design capability can save relationships where each person can amiably control a TV instance without bothering someone else near a single remote to do it. Second, the instances of TVRemote may carry their internal state separate from any state contained in a TV instance. For example, a TVRemote instance used by one person may have a dim light on the remote turned on to help operate in the dark.

Implementing an interface in a separate ...