0
0
Kotlinprogramming~30 mins

Visibility modifiers (public, private, internal, protected) in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Visibility modifiers (public, private, internal, protected)
📖 Scenario: You are creating a simple Kotlin class to understand how different visibility modifiers control access to class members.
🎯 Goal: Build a Kotlin class with properties and functions using public, private, internal, and protected visibility modifiers and observe how they affect access.
📋 What You'll Learn
Create a Kotlin class named Car with properties and functions using all four visibility modifiers.
Add a variable to hold the car's brand with public visibility.
Add a variable to hold the car's engine number with private visibility.
Add a function with internal visibility that returns the car's brand.
Add a protected function that returns the engine number.
Create a subclass SportsCar that tries to access the protected function.
Print outputs to show which members are accessible.
💡 Why This Matters
🌍 Real World
Visibility modifiers help protect sensitive data and control how parts of your code can be used or changed by others.
💼 Career
Understanding visibility is essential for writing safe, maintainable Kotlin code in professional Android or backend development.
Progress0 / 4 steps
1
Create the Car class with public and private properties
Create a Kotlin class called Car. Inside it, declare a public variable brand of type String and set it to "Toyota". Also declare a private variable engineNumber of type String and set it to "ENG12345".
Kotlin
Need a hint?

Use val brand: String = "Toyota" and private val engineNumber: String = "ENG12345" inside the class.

2
Add an internal function to get the brand
Inside the Car class, add an internal function called getBrand that returns the brand variable.
Kotlin
Need a hint?

Define internal fun getBrand(): String that returns brand.

3
Add a protected function to get the engine number
Inside the Car class, add a protected function called getEngineNumber that returns the engineNumber variable.
Kotlin
Need a hint?

Define protected fun getEngineNumber(): String that returns engineNumber.

4
Create SportsCar subclass and print accessible members
Create a subclass called SportsCar that inherits from Car. Inside it, create a function showDetails that prints the brand and calls the protected function getEngineNumber(). Then, in the main function, create a SportsCar object and print the result of calling getBrand() and showDetails().
Kotlin
Need a hint?

Create SportsCar subclass with showDetails() printing brand and getEngineNumber(). Then print getBrand() and call showDetails() in main().