0
0
Kotlinprogramming~30 mins

Inner classes and nested classes in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Inner classes and nested classes
📖 Scenario: You are creating a simple Kotlin program to understand how inner classes and nested classes work. Imagine you have a Car that has an Engine. The Engine can be represented as an inner class because it needs to access the Car details. You also want to have a CarInfo nested class that just holds some static information about cars.
🎯 Goal: Build a Kotlin program that defines a Car class with an Engine inner class and a CarInfo nested class. Then create objects and print details showing how inner and nested classes work.
📋 What You'll Learn
Create a class called Car with a property brand of type String set to "Toyota"
Inside Car, create an inner class called Engine with a function start() that returns a string "Engine of [brand] started"
Inside Car, create a nested class called CarInfo with a function info() that returns the string "Cars are vehicles"
Create an instance of Car, then create an instance of Engine from that car, and call start()
Call the info() function from the CarInfo nested class
Print the results of both function calls
💡 Why This Matters
🌍 Real World
Inner and nested classes help organize code that logically belongs together, like parts of a car. This keeps code clean and easier to maintain.
💼 Career
Understanding inner and nested classes is important for Kotlin developers working on Android apps or backend services, where encapsulation and code organization matter.
Progress0 / 4 steps
1
Create the Car class with brand property
Create a class called Car with a property brand of type String set to "Toyota".
Kotlin
Need a hint?

Use val brand: String = "Toyota" inside the Car class.

2
Add inner Engine class with start() function
Inside the Car class, create an inner class called Engine with a function start() that returns the string "Engine of [brand] started" using the brand property.
Kotlin
Need a hint?

Remember to use the inner keyword so Engine can access brand.

3
Add nested CarInfo class with info() function
Inside the Car class, create a nested class called CarInfo with a function info() that returns the string "Cars are vehicles".
Kotlin
Need a hint?

Use a normal nested class (no inner) for CarInfo.

4
Create instances and print results
Create an instance of Car called myCar. Then create an instance of Engine from myCar called myEngine and call start(). Also call the info() function from the CarInfo nested class. Finally, print both results.
Kotlin
Need a hint?

Remember to create Engine instance from myCar and call start(). Call info() from Car.CarInfo().