Nested and Inner Classes

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 class has drawbacks—the methods of TVRemote that implement the Remote interface have to use the public methods of the TV. If the TV implements the interface, then we don’t have to rely on any public methods, and also the implementation can efficiently use internals visible only within the class. And, instead of passing an instance of TV to the constructor of TVRemote, if we implement the interface directly in TV, we don’t need the extra references kept within instances of TVRemote.

The inner keyword

An alternative design option can help us keep the pros and at the same time avoid the cons. Using inner classes we can get the benefits offered by having the separate class, but without compromising efficiency. While the solution that follows may appear esoteric at first sight, this technique is used extensively in C#, Java, and Kotlin to implement iterators on collections.

In Kotlin a class may be nested—placed inside—another class. Unlike in Java, Kotlin nested classes can’t access the private members of the nesting outer class. But if you mark the nested class with the inner keyword, then they turn into inner classes and the restriction goes away.

Let’s move the TVRemote class from the previous example to be an inner class of TV:

Get hands-on with 1200+ tech skills courses.