Companion Objects and Class Members

The classes we created so far had properties and instance methods. If a property or a method is needed at the class level and not on a specific instance of the class, we can’t drop them into the class. Instead, place them in a companion object. In Singleton with Object Declaration, we created singletons. Companion objects are singletons defined within a class—they’re singleton companions of classes. In addition, companion objects may implement interfaces and may extend from base classes, and thus are useful with code reuse as well.

Class-level members

In the next example, a MachineOperator class needs a property and a method at the class level; we achieve that using a companion object:

Get hands-on with 1200+ tech skills courses.