android-kotlin
/

Kotlin OOP – Classes, Objects, and Inheritance

Last Sync: Today

On this page

5
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

android-kotlin

Kotlin OOP – Classes, Objects, and Inheritance

Classes and Constructors

In Kotlin, classes are declared using the class keyword. The most striking difference from Java is the Primary Constructor, which is part of the class header itself. This makes property declaration incredibly concise. As an Architect, you'll appreciate how this reduces 'boilerplate' noise in your native Android models.

KOTLINRead-only
1
// A class with a primary constructor and default values
class Project(val id: String, var name: String, val isPublic: Boolean = false) {
    init {
        println("Initializing project: $name")
    }
}

// Usage
val myProject = Project("rev_01", "AI Builder")

  1. Data Classes: The Perfect Models

When a class is created primarily to hold data (like a JSON response from your Python backend), you mark it as a data class. The compiler automatically generates equals(), hashCode(), toString(), and the powerful copy() function. This is far more advanced than standard Dart classes and saves hours of manual coding.

KOTLINRead-only
1
data class User(val uid: String, val email: String)

val user1 = User("123", "k@test.com")
// Create a new instance with one property changed
val user2 = user1.copy(email = "new@test.com")

  1. Inheritance and 'open' Classes

By default, all classes in Kotlin are final (cannot be inherited). To allow a class to be a parent, you must explicitly mark it with the open keyword. This 'Design for Inheritance' philosophy prevents accidental architectural fragility in your native Android modules.

KOTLINRead-only
1
open class BaseWidget(val type: String) {
    open fun render() = println("Rendering $type")
}

class ButtonWidget : BaseWidget("Button") {
    override fun render() {
        super.render()
        println("Applying shadow...")
    }
}

  1. Sealed Classes: State Management Pro

Sealed classes are used for representing restricted class hierarchies. They are essentially 'Enums on steroids.' For a Flutter Architect, they are the ideal way to represent UI States (Loading, Success, Error) when passing data back through a Method Channel.

KOTLINRead-only
1
sealed class UIState {
    object Loading : UIState()
    data class Success(val data: List<String>) : UIState()
    data class Error(val message: String) : UIState()
}

// Comprehensive handling in 'when'
fun handleState(state: UIState) = when(state) {
    is UIState.Loading -> showSpinner()
    is UIState.Success -> showList(state.data)
    is UIState.Error -> showError(state.message)
}

  1. Objects and Companion Objects

Kotlin doesn't have static members. Instead, it uses object for Singletons and companion object for members that belong to a class. This makes the Singleton pattern a first-class language feature.

FeatureKotlin OOPDart (Flutter) OOP
Default VisibilityPublicPublic
ImmutabilityClasses are final by defaultClasses are open by default
Static MembersCompanion Objectsstatic keyword
Data ModelsData Classes (Autogen)Manual / Code Gen
EnumsEnums / Sealed ClassesEnums / Sealed Classes
ConstructorsPrimary & SecondaryGenerative & Named

Test Your Knowledge

Q1
of 3

Which keyword is required to allow a Kotlin class to be inherited by another class?

A
public
B
open
C
abstract
D
static
Q2
of 3

Which specific class type provides autogenerated copy() and toString() methods?

A
Sealed Class
B
Object Class
C
Data Class
D
Inner Class
Q3
of 3

What is the Kotlin equivalent of a static block or static method?

A
Companion Object
B
Static Object
C
Init Block
D
Module Object

Frequently Asked Questions

What is the difference between a Class and an Object?

A 'class' is a blueprint for creating instances. An 'object' is a keyword used to define a Singleton—a class that has exactly one instance created automatically by the system.

Can a class have multiple constructors?

Yes. While the primary constructor is most common, you can define secondary constructors using the 'constructor' keyword. However, they must always call the primary constructor.

Why use Sealed Classes over Enums?

Enums are for constant values. Sealed classes are for types. Each branch of a sealed class can have its own unique properties and state (like an Error message or a Data list), which Enums cannot do effectively.

Previous

kotlin functions

Next

kotlin classes

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.