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 classPrint 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