Kotlin Visibility and Modifiers Tutorial: Public, Private, Protected, Internal, Open, Final, and Override
This Kotlin Visibility and Modifiers tutorial explains how to control access to classes, properties, and functions using visibility modifiers (public, private, protected, internal) and how to control inheritance behavior using open, final, and override keywords. The tutorial includes practical examples and best practices to help developers write secure, maintainable, and reusable Kotlin code.
Kotlin Visibility and Modifiers – Complete Tutorial
Visibility Modifiers
Visibility modifiers control the accessibility of classes, objects, interfaces, functions, and properties.
1. public
- Default modifier in Kotlin.
- Accessible from anywhere.
2. private
- Accessible only within the class or file (for top-level declarations).
3. protected
- Accessible within the class and its subclasses.
4. internal
- Accessible within the same module.
Best Practices for Visibility
- Keep properties and methods as private by default.
- Use public only for API-facing members.
- Use protected for inheritance purposes.
- Use internal to expose members only within a module.
Modifiers Controlling Inheritance
1. open
- Allows classes and methods to be inherited or overridden.
- By default, all classes and functions are
final.
2. final
- Prevents further inheritance or overriding.
- Default for all classes and functions.
3. override
- Used to override an open method or property in a subclass.
Best Practices for Modifiers
- Prefer
finalfor classes and methods unless inheritance is required. - Mark only necessary methods as
opento prevent accidental overrides. - Always use
overrideexplicitly when overriding a method.
Summary
This chapter explained Kotlin’s visibility modifiers (public, private, protected, internal) and inheritance-related modifiers (open, final, override). Proper use of these modifiers ensures code security, clarity, and maintainability while providing controlled flexibility in object-oriented designs.