When developing Android applications using Kotlin and Jetpack Compose, we need a structured way to organize data and functionality.
For example, an Android application may need to represent:
- User profiles
- Shopping cart products
- Bank accounts
- Expense transactions
- Music playlists
- Application settings
- Game characters
- API response models
Instead of storing every value separately, Kotlin allows us to group related data and behavior using classes and objects.
Classes are one of the fundamental concepts of object-oriented programming (OOP).
In this tutorial, we’ll explore Kotlin classes, objects, constructors, properties, member functions, initialization blocks, visibility modifiers, and practical Android examples.
What You’ll Learn
By the end of this tutorial, you’ll understand:
- What object-oriented programming is
- What classes are in Kotlin
- What objects are
- How to create and use objects
- Class properties
- Member functions
- Primary constructors
- Secondary constructors
- The
initblock - Default property values
- Custom getters and setters
- Visibility modifiers
- The
thiskeyword - Class vs object declarations
- Practical Android examples
- Using Kotlin classes in Jetpack Compose
- Common beginner mistakes
Let’s begin!
1. What Is Object-Oriented Programming?
Object-oriented programming, commonly called OOP, is a programming approach that organizes code around objects.
An object can contain:
- Properties: Data describing the object.
- Methods: Functions defining what the object can do.
For example, consider a user in an Android application.
A user may have the following properties:
Name: Alex
Age: 25
City: Hyderabad
The user may also perform actions such as:
Display Profile
Update Name
Check Eligibility
Instead of managing this information separately, we can represent the user using a Kotlin class.
Kotlin supports object-oriented programming along with functional programming features.
2. What Is a Class in Kotlin?
A class is a blueprint for creating objects.
A class defines the properties and functions that its objects can have.
Syntax
class ClassName {
// Properties
// Member functions
}
Example
class User {
var name = "Alex"
var age = 25
}
Here:
Useris the class name.nameis a property.ageis another property.
However, declaring a class doesn’t automatically create an instance of it.
To use the class, we create an object.
3. How to Create an Object in Kotlin
An object is an instance of a class.
Example
class User {
var name = "Alex"
var age = 25
}
fun main() {
val user = User()
println(user.name)
println(user.age)
}
Output:
Alex
25
How It Works
The expression:
User()
creates a new instance of the User class.
The variable:
val user = User()
stores a reference to that object.
We access its properties using the dot operator:
user.name
user.age
4. Creating Multiple Objects
A class can be used to create multiple objects.
Each object has its own instance properties.
Example
class Student {
var name = ""
var marks = 0
}
fun main() {
val student1 = Student()
student1.name = "Alex"
student1.marks = 90
val student2 = Student()
student2.name = "Emma"
student2.marks = 85
println("${student1.name}: ${student1.marks}")
println("${student2.name}: ${student2.marks}")
}
Output:
Alex: 90
Emma: 85
Explanation
Both objects are created from the same class.
However, they store different property values.
This is useful when representing multiple users, products, or other application entities.
5. Kotlin Class Properties
Properties represent the data stored by an object.
Kotlin provides two primary property declaration keywords.
| Keyword | Description |
|---|---|
val | Read-only property reference or value |
var | Mutable property that can be reassigned |
Example
class Product {
val productId = 101
var price = 500
}
Usage
fun main() {
val product = Product()
println(product.productId)
product.price = 750
println(product.price)
}
Output:
101
750
Important
A val property cannot be reassigned after initialization through ordinary code.
A var property can be updated.
For maintainable Kotlin code, prefer val unless reassignment is necessary.
6. Kotlin Member Functions
Functions declared inside a class are called member functions.
They define behavior associated with the class.
Example
class Calculator {
fun add(a: Int, b: Int): Int {
return a + b
}
fun multiply(a: Int, b: Int): Int {
return a * b
}
}
Usage
fun main() {
val calculator = Calculator()
println(calculator.add(10, 20))
println(calculator.multiply(5, 4))
}
Output:
30
20
Explanation
The Calculator class contains two member functions:
add()multiply()
We call these functions using the object reference.
calculator.add(10, 20)
Member functions are useful for grouping related behavior.
7. What Is a Constructor in Kotlin?
A constructor initializes an object when it is created.
Kotlin supports:
- Primary constructors
- Secondary constructors
Constructors help us provide initial property values and enforce required information.
Let’s explore them.
8. Kotlin Primary Constructor
A primary constructor is declared as part of the class header.
Example
class User(
val name: String,
val age: Int
)
Usage
fun main() {
val user = User(
name = "Alex",
age = 25
)
println(user.name)
println(user.age)
}
Output:
Alex
25
How It Works
The constructor accepts two values:
name: String
age: Int
Because both parameters use val, Kotlin automatically creates read-only properties.
Important
Constructor parameters declared without val or var are not automatically exposed as object properties.
For example:
class Greeting(name: String) {
val message = "Hello, $name"
}
Here, message is a property, while name is a constructor parameter.
9. Primary Constructor with Mutable Properties
We can use var when properties need to change.
Example
class BankAccount(
val accountNumber: String,
var balance: Int
)
Usage
fun main() {
val account = BankAccount(
accountNumber = "ACC001",
balance = 5000
)
account.balance += 1000
println(account.balance)
}
Output:
6000
Best Practice
For important business data such as account balances, avoid exposing unrestricted public mutation in production code.
Instead, use controlled methods that validate updates.
We’ll explore encapsulation later in this tutorial.
10. Kotlin Default Constructor Parameters
Kotlin supports default values in constructors.
Example
class User(
val name: String,
val city: String = "Unknown"
)
Usage
fun main() {
val user1 = User("Alex")
val user2 = User(
name = "Emma",
city = "Hyderabad"
)
println(user1.city)
println(user2.city)
}
Output:
Unknown
Hyderabad
Benefits
Default constructor parameters help:
- Reduce repetitive arguments
- Make object creation easier
- Improve readability
- Provide sensible default values
Default arguments are widely used in Kotlin and Jetpack Compose APIs.
11. Kotlin init Block
Kotlin provides the init block to execute initialization logic when an object is created.
Example
class User(
val name: String,
val age: Int
) {
init {
println("User object created")
}
}
Usage
fun main() {
val user = User("Alex", 25)
println(user.name)
}
Output:
User object created
Alex
Why Use init?
The init block can be useful for:
- Validating constructor arguments
- Performing initialization calculations
- Preparing initial object state
Practical Example: Validation
class Product(
val name: String,
val price: Int
) {
init {
require(price >= 0) {
"Price cannot be negative"
}
}
}
If a negative price is supplied, require() throws an IllegalArgumentException.
This prevents creation of an object with an invalid price.
12. Kotlin Secondary Constructors
A secondary constructor provides an additional way to initialize an object.
Kotlin uses the constructor keyword.
Example
class Employee {
val name: String
val department: String
constructor(name: String) {
this.name = name
this.department = "General"
}
constructor(
name: String,
department: String
) {
this.name = name
this.department = department
}
}
Usage
fun main() {
val employee1 = Employee("Alex")
val employee2 = Employee(
"Emma",
"Engineering"
)
println(employee1.department)
println(employee2.department)
}
Output:
General
Engineering
Important
If a class has a primary constructor, its secondary constructors must delegate to the primary constructor, directly or indirectly, using this(...).
For many simple use cases, primary constructors with default parameters are easier to maintain than multiple secondary constructors.
13. Kotlin this Keyword
The this keyword refers to the current object.
It is useful when distinguishing properties from parameters with similar names.
Example
class User {
var name: String = ""
fun updateName(name: String) {
this.name = name
}
}
Usage
fun main() {
val user = User()
user.updateName("Alex")
println(user.name)
}
Output:
Alex
Explanation
Inside the function:
this.name
refers to the object’s property.
The parameter:
name
refers to the value passed into the function.
The this keyword makes the distinction clear.
14. Kotlin Custom Getters and Setters
Kotlin allows properties to define custom getter and setter behavior.
Example
class Employee {
var salary: Int = 0
set(value) {
require(value >= 0) {
"Salary cannot be negative"
}
field = value
}
}
Usage
fun main() {
val employee = Employee()
employee.salary = 50000
println(employee.salary)
}
Output:
50000
What Is field?
Inside a property accessor, field refers to the backing field when one exists.
It allows the setter to update the stored property value without recursively calling itself.
Custom Getter Example
class Rectangle(
val width: Int,
val height: Int
) {
val area: Int
get() = width * height
}
Usage
val rectangle = Rectangle(10, 5)
println(rectangle.area)
Output:
50
The area is calculated whenever the property is accessed.
15. Kotlin Visibility Modifiers
Visibility modifiers control where classes, properties, and functions can be accessed.
Kotlin provides four main visibility modifiers.
| Modifier | Description |
|---|---|
public | Accessible wherever the declaration is visible |
private | Restricted to the relevant declaration scope |
protected | Accessible in a class and its subclasses |
internal | Accessible within the same module |
Example: Private Property
class BankAccount {
private var balance = 1000
fun getBalance(): Int {
return balance
}
}
Usage
fun main() {
val account = BankAccount()
println(account.getBalance())
}
Output:
1000
The property balance cannot be accessed directly from outside the class.
Why Is This Useful?
Visibility modifiers help protect internal implementation details and prevent unintended access.
This is an important part of encapsulation.
16. Kotlin Encapsulation
Encapsulation means controlling access to an object’s internal state and behavior.
Instead of allowing external code to modify important values freely, we can provide methods that enforce business rules.
Example
class Wallet(
initialBalance: Int
) {
var balance: Int = initialBalance
private set
init {
require(initialBalance >= 0)
}
fun deposit(amount: Int) {
require(amount > 0)
balance += amount
}
fun withdraw(amount: Int): Boolean {
if (amount <= 0 || amount > balance) {
return false
}
balance -= amount
return true
}
}
Usage
fun main() {
val wallet = Wallet(1000)
wallet.deposit(500)
wallet.withdraw(300)
println(wallet.balance)
}
Output:
1200
Explanation
External code can read:
wallet.balance
But cannot directly assign a new balance because the setter is private.
Updates must go through:
deposit()
withdraw()
This gives the class control over how its state changes.
For production financial systems, additional considerations such as precise money representations, overflow checks, persistence, concurrency, and transaction integrity are necessary.
17. Kotlin Class vs Object Declaration
Kotlin provides both class declarations and object declarations.
Class Declaration
class UserManager
To create an instance:
val manager = UserManager()
You can create multiple instances.
Object Declaration
object AppConstants {
const val APP_NAME = "Moiks Developer Blog"
const val MAX_RETRY_COUNT = 3
}
Usage
fun main() {
println(AppConstants.APP_NAME)
}
Output:
Moiks Developer Blog
An object declaration creates a named singleton object.
You don’t call a constructor to access it.
When Should You Use object?
Object declarations are useful for:
- Constants
- Stateless utilities
- Shared configuration
- Singleton implementations when appropriate
Avoid storing mutable global application state in singleton objects without considering lifecycle, concurrency, and testability.
18. Kotlin Companion Objects
A companion object allows declarations to be accessed through the containing class name.
Example
class User {
companion object {
const val DEFAULT_ROLE = "Guest"
fun createGuest(): User {
return User()
}
}
}
Usage
fun main() {
println(User.DEFAULT_ROLE)
val guest = User.createGuest()
println(guest)
}
A companion object is useful for factory functions and constants associated with a class.
Important
Kotlin companion objects are objects associated with their containing classes, not Java-style static declarations.
They offer similar convenient class-name access for many use cases.
19. Practical Android Example: Product Model
Let’s create a simple product class for an Android shopping application.
Product Class
class Product(
val id: Int,
val name: String,
val price: Int,
var quantity: Int = 1
) {
init {
require(price >= 0)
require(quantity >= 0)
}
fun calculateTotal(): Int {
return price * quantity
}
fun increaseQuantity() {
quantity++
}
}
Usage
fun main() {
val product = Product(
id = 101,
name = "Wireless Headphones",
price = 1499,
quantity = 2
)
println(product.name)
println(product.calculateTotal())
product.increaseQuantity()
println(product.calculateTotal())
}
Output:
Wireless Headphones
2998
4497
What We Used
This example demonstrates:
- Class declaration
- Primary constructor
- Properties
- Default arguments
initblock- Member functions
- Mutable state
- Object creation
These concepts form the foundation of many Android data models.
20. Kotlin Classes in Android Development
Kotlin classes are used throughout Android applications.
For example:
Activity Classes
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
Text("Hello Android")
}
}
}
An Activity is a class that participates in the Android lifecycle.
ViewModel Classes
class HomeViewModel : ViewModel() {
fun loadData() {
// Load screen data
}
}
ViewModels help manage UI-related state and logic.
Repository Classes
class UserRepository {
fun getUsername(): String {
return "Alex"
}
}
Repositories organize data access responsibilities.
These are simplified examples. We’ll explore Android architecture and ViewModel in dedicated tutorials.
21. Jetpack Compose Mini-Project: Product Details Screen
Let’s build a simple Jetpack Compose screen using a Kotlin class.
We’ll create:
- A product model
- Product name and price display
- Quantity controls
- Automatic total calculation
Step 1: Create the Product Class
class ShopProduct(
val id: Int,
val name: String,
val price: Int
) {
init {
require(price >= 0)
}
fun calculateTotal(quantity: Int): Int {
require(quantity >= 0)
return price * quantity
}
}
Step 2: Create the Compose Screen
@Composable
fun ProductDetailsScreen() {
val product = remember {
ShopProduct(
id = 101,
name = "Wireless Headphones",
price = 1499
)
}
var quantity by rememberSaveable {
mutableIntStateOf(1)
}
val total = product.calculateTotal(quantity)
Column(
modifier = Modifier
.fillMaxSize()
.padding(24.dp),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = "Product Details",
style = MaterialTheme.typography.headlineMedium
)
Spacer(
modifier = Modifier.height(24.dp)
)
Card(
modifier = Modifier.fillMaxWidth()
) {
Column(
modifier = Modifier.padding(20.dp),
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
Text(
text = product.name,
style = MaterialTheme.typography.titleLarge
)
Text(
text = "Price: ₹${product.price}",
style = MaterialTheme.typography.bodyLarge
)
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(16.dp)
) {
Button(
onClick = {
if (quantity > 1) {
quantity--
}
},
enabled = quantity > 1
) {
Text("-")
}
Text(
text = quantity.toString(),
style = MaterialTheme.typography.titleMedium
)
Button(
onClick = {
quantity++
}
) {
Text("+")
}
}
Text(
text = "Total: ₹$total",
style = MaterialTheme.typography.titleLarge,
color = MaterialTheme.colorScheme.primary
)
}
}
}
}
Required Imports
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
Expected UI
+--------------------------------+
| |
| Product Details |
| |
| +----------------------------+ |
| | | |
| | Wireless Headphones | |
| | | |
| | Price: ₹1499 | |
| | | |
| | [-] 2 [+] | |
| | | |
| | Total: ₹2998 | |
| | | |
| +----------------------------+ |
| |
+--------------------------------+
How It Works
We created a Kotlin class:
class ShopProduct(
val id: Int,
val name: String,
val price: Int
)
This class represents the product.
We also created a member function:
fun calculateTotal(quantity: Int): Int
This calculates the total price.
In Jetpack Compose, the quantity is stored using observable state:
var quantity by rememberSaveable {
mutableIntStateOf(1)
}
When the user taps the increment or decrement button, the quantity changes.
Jetpack Compose recomposes the relevant UI and recalculates the total.
Why This Design?
The product class handles product-related calculations.
The composable handles UI presentation and user interaction.
This separation makes code easier to maintain.
In production applications, more complex business logic is often moved into ViewModels, use cases, or domain-layer components.
22. Common Kotlin Classes and Objects Mistakes
Mistake 1: Forgetting to Create an Object
Incorrect:
class User {
val name = "Alex"
}
println(User.name)
A regular instance property cannot be accessed directly through the class name.
Correct:
val user = User()
println(user.name)
Mistake 2: Confusing Class and Object
A class defines how instances are created.
An object is an instance.
class Car(
val brand: String
)
val car = Car("Toyota")
Here, Car is the class and car references an object.
Mistake 3: Forgetting val or var in Constructor Properties
Consider:
class User(name: String)
Here, name is a constructor parameter, not a publicly accessible property.
If you want to expose it as a property:
class User(val name: String)
Mistake 4: Exposing Important Mutable Properties
Avoid unrestricted mutation of sensitive business state.
Instead of:
class Wallet {
var balance = 1000
}
Prefer controlled access:
class Wallet {
var balance = 1000
private set
fun deposit(amount: Int) {
require(amount > 0)
balance += amount
}
}
Mistake 5: Putting Too Much Logic in One Class
Avoid creating large classes that handle unrelated responsibilities.
For example, a single class shouldn’t manage UI, networking, database access, and business rules all at once.
As your application grows, separate responsibilities using appropriate architectural layers.
23. Kotlin Classes and Objects Quick Reference
| Concept | Example |
|---|---|
| Class | class User |
| Object creation | val user = User() |
| Property | val name = "Alex" |
| Mutable property | var age = 25 |
| Member function | fun greet() { } |
| Primary constructor | class User(val name: String) |
| Secondary constructor | constructor(name: String) |
| Initialization block | init { } |
| Default parameter | val city: String = "Unknown" |
| Current object | this |
| Private property | private var balance = 0 |
| Custom getter | get() = width * height |
| Custom setter | set(value) { field = value } |
| Singleton object | object AppConstants |
| Companion object | companion object { } |
24. Practical Exercises
Try these exercises to strengthen your Kotlin OOP skills.
Exercise 1: Student Class
Create a Student class with:
- Name
- Roll number
- Marks
Create three student objects and display their details.
Exercise 2: Rectangle Calculator
Create a Rectangle class with width and height properties.
Add functions to calculate:
- Area
- Perimeter
Exercise 3: Bank Account
Create a BankAccount class with:
- Private balance
- Deposit function
- Withdraw function
- Balance getter
Prevent invalid withdrawals.
Exercise 4: Employee Class
Create an Employee class using a primary constructor.
Add default values for optional properties.
Exercise 5: Companion Object
Create an AppConfig class containing a companion object with application constants.
Exercise 6: Jetpack Compose Product Card
Create a reusable product card that displays:
- Product name
- Price
- Quantity
- Total amount
Use a Kotlin class to calculate the total.
What We’ve Learned
In this tutorial, we learned:
- What object-oriented programming is
- Kotlin classes and objects
- Creating multiple instances
- Class properties
- Member functions
- Primary constructors
- Secondary constructors
- Default constructor parameters
- Initialization blocks
- The
thiskeyword - Custom getters and setters
- Visibility modifiers
- Encapsulation
- Object declarations
- Companion objects
- Practical Android data models
- Kotlin classes in Jetpack Compose
- Common OOP mistakes
Kotlin classes and objects provide the foundation for organizing data and behavior in Android applications.
As we continue learning Kotlin, these concepts will become increasingly important when working with data classes, inheritance, interfaces, ViewModels, repositories, and Clean Architecture.
What’s Next?
In our next tutorial, we’ll explore:
Kotlin Inheritance and Interfaces Explained with Examples
You’ll learn:
- What inheritance is
- The
openkeyword - Extending Kotlin classes
- Method overriding
- The
superkeyword - Abstract classes
- Interfaces
- Implementing multiple interfaces
- Inheritance vs composition
- Practical Android examples
Happy Coding!
Continue learning modern Android development with Moiks Developer Blog.